vue动态子组件的两种实现方式

2020-06-12 21:15:11易采站长站整理

}
})
</script>

activated 和 deactivated

activated 和 deactivated 在 <keep-alive> 树内的所有嵌套组件中触发:


<div id="example">
<button @click="change">切换页面</button>
<keep-alive>
<component :is="currentView" @pass-data="getData"></component>
</keep-alive>
<p>{{msg}}</p>
</div>

<script>
new Vue({
el: '#example',
data:{
index:0,
msg:'',
arr:[
{
template:`<div>我是主页</div>`,
activated(){
this.$emit('pass-data','主页被添加');
},
deactivated(){
this.$emit('pass-data','主页被移除');
},
},
{template:`<div>我是提交页</div>`},
{template:`<div>我是存档页</div>`}
],
},
computed:{
currentView(){
return this.arr[this.index];
}
},
methods:{
change(){
var len = this.arr.length;
this.index = (++this.index)% len;
},
getData(value){
this.msg = value;
setTimeout(()=>{
this.msg = '';
},500)
}
}
})
</script>

include和exclude

include 和exclude属性允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示:


<!-- 逗号分隔字符串 -->
<keep-alive include="a,b">
<component :is="view"></component>
</keep-alive>
<!-- 正则表达式 (使用 v-bind) -->
<keep-alive :include="/a|b/">
<component :is="view"></component>
</keep-alive>
<!-- Array (use v-bind) -->
<keep-alive :include="['a', 'b']">
<component :is="view"></component>
</keep-alive>

匹配首先检查组件自身name选项,如果name选项不可用,则匹配它的局部注册名称(父组件 components 选项的键值)。匿名组件不能被匹配。


<keep-alive include="home,archive">
<component :is="currentView"></component>
</keep-alive>

上面的代码,表示只缓存home和archive,不缓存posts

方式二:动态注册组件实现


asyncComponents(templateName){
this.curNavComponents = require(`./components/${templateName}.vue`).default;
}

总结

以上所述是小编给大家介绍的vue动态子组件的两种实现方式,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!