Vue动态组件
通过组件的学习我们已经了解了组件的基本使用,但是我们以前使用的组件都是静态的,也就是说它是固定名字的那一个组件,今天我学习到了动态组件,它可以动态的更改自己的组件名,感觉很方便~
我们可以在组件中通过 :is 来实现动态组件
具体代码如下
<div id="app">
<div id="content">
<component :is="com"></component>
</div>
<button @click="chooseContent(1)">首页</button>
<button @click="chooseContent(2)">列表</button>
<button @click="chooseContent(3)">新闻</button>
<button @click="chooseContent(4)">个人</button>
</div>
let com1 = Vue.component("index-com",{
template: "<h1>首页内容</h1>",
})
let com2 = Vue.component("list-com",{
template: "<h1>列表内容</h1>",
})
let com3 = Vue.component("news-com",{
template: "<h1>新闻内容</h1>",
})
let com4 = Vue.component("me-com",{
template: "<h1>个人内容</h1>",
})
var app = new Vue({
el: "#app",
data: {
com: com1
},
methods: {
chooseContent: function(id){
// console.log(id);
// console.log(this);
// 通过获取id,选择注册好的组件
this.com = this.$options.components["com"+id]
}
},
components: {
com1,com2,com3,com4
}
})
上面代码中的 this.$options 是Vue的自带属性,我们可以通过它来找到我们自定义的组件( com1, com2, com3, com4 )
现在就已经实现了基本的动态组件,让我们看一下效果吧
当然,这种动态组件的方法肯定是不常用的,这只是学习阶段记录一下笔记而已,后面可能要使用 Vue 脚手架中的单文件组件(.vue )
态组件的方法肯定是不常用的,这只是学习阶段记录一下笔记而已,后面可能要使用 Vue 脚手架中的单文件组件(.vue )