动态组件 传送门
在一个元素上挂载多个组件,根据不同状态进行切换的时候,可以使用动态组件
动态组件的使用:需要使用内置组件<component></component>,根据 :is 的值决定显示哪个组件,:is的值是要显示的组件id
目录结构
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Gary</title>
</head>
<body>
<div id="GaryId">
<button @click="selectedName = 'my-component-a'"> a </button>
<button @click="selectedName = 'my-component-b'"> b </button>
<button @click="selectedName = 'my-component-c'"> c </button> <component :is="selectedName"></component> </div>
</body> <script type="text/javascript" src="../js/vue.js" ></script>
<script type="text/javascript"> new Vue({
data:{
selectedName:'my-component-a'
},
components:{
"my-component-a":{
template:"<h1>Hello Vue</h1>"
},
"my-component-b":{
template:"<a href='https://www.cnblogs.com/1138720556Gary/'>Gary博客</a>"
},
"my-component-c":{
template:"<p>欢迎来到Gary博客</p>"
}
}
}).$mount("#GaryId");
</script>
</html>
Gary_dynamic_component.html
实现过程
Vue的data域中为组件申请一个名称
data:{
selectedName:'my-component-a'
},
<div>标签中标明使用'my-component-a'组件模板
<div id="GaryId">
<button @click="selectedName = 'my-component-a'"> a </button>
<button @click="selectedName = 'my-component-b'"> b </button>
<button @click="selectedName = 'my-component-c'"> c </button> <component :is="selectedName"></component> </div>
在Vue的components中标明组件模块
new Vue({
data:{
selectedName:'my-component-a'
},
components:{
"my-component-a":{
template:"<h1>Hello Vue</h1>"
},
"my-component-b":{
template:"<a href='https://www.cnblogs.com/1138720556Gary/'>Gary博客</a>"
},
"my-component-c":{
template:"<p>欢迎来到Gary博客</p>"
}
}
}).$mount("#GaryId");