~ Vue 动态组件

有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:

上述内容可以通过 Vue 的 <component>元素加一个特殊的 is特性来实现:

<!-- 组件会在 `currentTabComponent` 改变时改变 -->
<component v-bind:is="currentTabComponent"></component>

动态(子)组件的实现方式

  • 动态组件就是几个组件放在一个挂载点下,然后根据父组件的某个变量来决定显示哪个,或者都不显示。
  • 在挂载点使用 component 标签,然后使用 is =“组件名”,它会自动去找匹配的组件名,如果有,则显示。

<div id="example">
  <button @click="change">切换页面</button>
  <component :is="currentView"></component>
</div>
var home = {template:'<div>我是主页</div>'};
var post = {template:'<div>我是提交页</div>'};
var archive = {template:'<div>我是存档页</div>'};
new Vue({
  el: '#example',
  components: {
    home,
    post,
    archive,
  },
  data:{
    index:0,
    arr:['home','post','archive'],
  },
  computed:{
    currentView(){
        return this.arr[this.index];
    }
  },
  methods:{
    change(){
      this.index = (++this.index)%3;
    }
  }
})
</script>

在动态组件上使用 keep-alive 缓存

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition>相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在父组件链中。

// 基本用法

<div id="example">
  <button @click="change">切换页面</button>
  <keep-alive>
    <component :is="currentView"></component>  
  </keep-alive>
</div>

[ 条件判断 ] 如果有多个条件性的子元素,<keep-alive> 要求同时只有一个子元素被渲染:

<div id="example">
  <button @click="change">切换页面</button>
  <keep-alive>
    <home v-if="index===0"></home>
    <posts v-else-if="index===1"></posts>
    <archive v-else></archive>  
  </keep-alive>
</div>

<script>
new Vue({
  el: '#example',
  components:{
    home:{template:`<div>我是主页</div>`},
    posts:{template:`<div>我是提交页</div>`},
    archive:{template:`<div>我是存档页</div>`},
  },
  data:{
    index:0,
  },
  methods:{
    change(){
      let len = Object.keys(this.$options.components).length;
      this.index = (++this.index)%len;
    }
  }
})
</script>