动态组件

1. component 组件

有时候我们需要在多个组件间切换,可以使用 <component> 组件和 is 属性实现。

动态组件调用:

<div id="app">
  <button @click="current = 'comA'">A</button>
  <button @click="current = 'comB'">B</button>

  <component v-bind:is="current"></component>
</div>
var vm = new Vue({
  el: "#app",
  data: {
    current: "comA"
  }
});

然而,我们发现在切换的时候,这些组件的 createdmounteddestroyed 函数都会被反复的调用,如果结合着某些业务逻辑的话,这样会产生不必要的开销。

2.keep-alive 组件

<div id="app">
  <button @click="current = 'comA'">A</button>
  <button @click="current = 'comB'">B</button>
  <!-- 在component组件外套一个keep-alive组件 -->
  <keep-alive>
    <component v-bind:is="current"></component>
  </keep-alive>
</div>

组件 A 中的表现:

Vue.component("comA", {
  template: "#temp-comA",
  data: function() {
    return {};
  },
  created() {
    console.log("A : created");
  },
  mounted() {
    console.log("A : mounted");
  },
  destroyed() {
    console.log("A : destroyed");
  },
  activated() {
    // 活动的状态,被切换到前台的时候
    console.log("A : activated");
  }
});

经过 keep-alive 的包裹,组件在被调用时的 createdmounted 只会被调用一次; destroyed 不再被触发,因为在切换时并没有真正销毁组件,而是放进缓存当中;组件被切换出来时会触发一个 actived 的生命周期函数;

Last Updated:
Contributors: zerojs