一、Vue官方文档
https://cn.vuejs.org/v2/guide/components.html#%E5%8A%A8%E6%80%81%E7%BB%84%E4%BB%B6
二、本文在此例子的基础上改动
三、例子
- /src/App.vue
<template>
<div id="app" class="demo">
<!--修改了这里,感觉index比key更直观-->
<button v-for="(tab, index) in tabs" @click="tabIndex = index">
{{ tab }}
</button>
<!--如果要传值,就只能在这里传-->
<component :is="change" msg="Hello World!"></component>
</div>
</template>
<script>
// 引入子组件
import Child from './components/Child';
export default {
name: 'test',
data() {
return {
tabIndex: 'home',
tabs: ['线路一','线路二','线路三'],
statu: ['lineOne','lineTwo','lineThr']
}
},
components: {
// 令线路一为子组件
lineOne: Child,
lineTwo: {template: '<div>我是线路二</div>'},
lineThr: {template: '<div>我是线路三</div>'},
},
computed: {
change() {
return this.statu[this.tabIndex]
}
}
}
</script>
<style scoped lang="scss">
</style>
- /src/components/Child.vue
<template>
<div>
<h2>{{ msg }}</h2>
</div>
</template>
<script>
export default {
name: 'child',
props: {
msg: {
required: true
}
}
}
</script>
<style scoped lang="scss">
</style>
1.一开始
2.点击了线路一
3.点击了线路二(线路三同理)
四、解析总结
这里一句话就能完成动态组件,虽然感觉传值还不够完美(可能是有更好的方法,欢迎提出)。
<component :is="change" msg="Hello World!"></component>
如果没有,就只能通过v-if判断,会很累赘。
<child v-if="tabIndex === 0" msg="Hello World!"></child>
<div v-if="tabIndex === 1">我是线路二</div>
<div v-if="tabIndex === 2">我是线路三</div>