动态组件是使用<compnent></compnent>
实现组件的切换,一般都会在组件外定义一个按钮,对组件的切换进行交互
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>动态组件</title>
</head>
<body>
<div id="app">
<button v-for="item in tabs" @click="curComponent=item">{{item.name}}</button>
<component :is="curComponent.component"></component>
<component-a></component-a>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
<script type="text/javascript">
// 一个组件的选项对象
// 已经注册的组件
// 局部组件
var componentA = {
data(){
return {}
},
template:"<div style='background:red;'></div>"
}
var tabs=[
{
// 指定了name值,叫做命名组件
name:"home",
component:{
template:"<div>{{content}}</div>",
data(){
return {
content:"IMHome"
}
}
},
},
{
name:"about",
component:{
template:"<div>IMAoubt</div>"
}
}
]
// 全局组件
// Vue.component("home",{
// template:"<div>IMHome</div>"
// })
// Vue.component("about",{
// template:"<div>IMAoubt</div>"
// })
var app = new Vue({
el:"#app",
data:{
tabs:tabs,
list:["home","about"],
curComponent:tabs[0]
},
components:{
// 注册局部组件
// 渲染局部组件
componentA:componentA
}
})
</script>
</body>
</html>
可以简单分为以下几步:
- 循环输出组件的按钮
<button v-for="item in tabs" @click="curComponent=item">{{item.name}}</button>
按钮时常会是中文名字之类的特定值,对此最好使用对象表示item,比如:
list:[{name:'home'},{name:'about'}]
使用这种数据结构就可以将标题和内容区分开来
- 使用
<component></component>
动态切换组件
<component :is="curComponent.component"></component>
通过绑定组件的
is
进行组件的切换,实际上,动态切换组件的原理就是用is
绑定组件的名字,在第一步中,通过点击事件将组件名字间接赋值到<component>
标签上,当:is
检测到组件名字的变换,就会切换到相应的组件上
但是,组件时常是在按钮以上或者以下,并不是包含在组件里面的,因此,最好在编译模板的时候将他们分开来
<template>
<div class="navtab">
<div class="addr">
广州<span class="downarr iconfont icon-weibiaoti1"></span>
</div>
<div class="btn fl" v-for="(item,index) in tabs" @click="change(item,index)" :class="{btnAct:index==bgNum}" >{{item.textname}}</div>
<keep-alive>
<component class="com" :is="curComponent" ></component>
</keep-alive>
<div class="search iconfont icon-fangdajing"></div>
</div>
</template>
网友评论