1. 程式人生 > >Vue 實現展開摺疊效果

Vue 實現展開摺疊效果

Vue 實現展開摺疊效果

效果參見:https://segmentfault.com/q/1010000011359250/a-1020000011360185

上述連結中,大佬給除了解決方法,再次進行總結,方便以後使用。

除了使用jQuery的方式實現上述效果,同樣可以在Vue實現,下面是解決辦法:

1、建立collapse.js檔案


const elTransition =
  "0.3s height ease-in-out, 0.3s padding-top ease-in-out, 0.3s padding-bottom ease-in-out";
const Transition = {
  "before-enter"(el) {
    el.style.transition = elTransition;
    if (!el.dataset) el.dataset = {};

    el.dataset.oldPaddingTop = el.style.paddingTop;
    el.dataset.oldPaddingBottom = el.style.paddingBottom;

    el.style.height = 0;
    el.style.paddingTop = 0;
    el.style.paddingBottom = 0;
  },

  enter(el) {
    el.dataset.oldOverflow = el.style.overflow;
    if (el.scrollHeight !== 0) {
      el.style.height = el.scrollHeight + "px";
      el.style.paddingTop = el.dataset.oldPaddingTop;
      el.style.paddingBottom = el.dataset.oldPaddingBottom;
    } else {
      el.style.height = "";
      el.style.paddingTop = el.dataset.oldPaddingTop;
      el.style.paddingBottom = el.dataset.oldPaddingBottom;
    }

    el.style.overflow = "hidden";
  },

  "after-enter"(el) {
    el.style.transition = "";
    el.style.height = "";
    el.style.overflow = el.dataset.oldOverflow;
  },

  "before-leave"(el) {
    if (!el.dataset) el.dataset = {};
    el.dataset.oldPaddingTop = el.style.paddingTop;
    el.dataset.oldPaddingBottom = el.style.paddingBottom;
    el.dataset.oldOverflow = el.style.overflow;

    el.style.height = el.scrollHeight + "px";
    el.style.overflow = "hidden";
  },

  leave(el) {
    if (el.scrollHeight !== 0) {
      el.style.transition = elTransition;
      el.style.height = 0;
      el.style.paddingTop = 0;
      el.style.paddingBottom = 0;
    }
  },

  "after-leave"(el) {
    el.style.transition = "";
    el.style.height = "";
    el.style.overflow = el.dataset.oldOverflow;
    el.style.paddingTop = el.dataset.oldPaddingTop;
    el.style.paddingBottom = el.dataset.oldPaddingBottom;
  }
};

export default {
  name: "collapseTransition",
  functional: true,
  render(h, { children }) {
    const data = {
      on: Transition
    };
    return h("transition", data, children);
  }
};

2、在.vue元件中引入



<template>
    <div class="container">
        <button @click="isActive = !isActive">展開/摺疊</button>
        <collapse>
            <div class="container" v-show="isActive">
                <h2>歡迎大家品嚐Pizza!</h2>
                <h5>這裡有你非常喜歡的Pizza!</h5>
            </div>
        </collapse>
    </div>
</template>
<script>
import collapse from "../assets/js/collapse.js";
export default {
  data() {
    return {
      isActive: false
    };
  },
  components: {
    collapse
  }
};
</script>

來源:https://segmentfault.com/a/1190000016160493