VueComponent动态组件切换时候的一个坑
<div id="app">
<button type="button"
@click="currentCompoent = $options.components.test1"
>test1</button>
<button type="button"
@click="currentCompoent = $options.components.test2"
>test2</button>
<button type="button"
@click="currentCompoent = $options.components.test3"
>test3</button>
<component :is="currentCompoent"></component>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
const test1 = {
template:`
<div id="test1">
<h2>test1</h2>
</div>
`
}
const test2 = {
template:`
<div id="test2">
<h2>test2</h2>
</div>
`
}
const test3 = {
template:`
<div id="test3">
<h2>test3</h2>
</div>
`
}
const app = new Vue({
el:"#app",
data:{
currentCompoent:test1
},
components:{
test1,
test2,
test3
},
methods:{
testChange1(){
// this.currentCompoent = test1
this.currentCompoent = this.$options.components.test1
},
testChange2(){
// this.currentCompoent = test2
this.currentCompoent = this.$options.components.test2
},
testChange3(){
// this.currentCompoent = test3
this.currentCompoent = this.$options.components.test3
}
}
})
</script>
Vue官网上是写着,currentCompoen可以是一个已注册的组件名字或者组件的选项对象。
在HTML模板里面访问不到配置项中的components,@click="currentComponent = test1",切换的时候会报错,从Vue实例身上取$options.components.test1即可正确拿到test1这个组件。
Vue实例上的data和methods也访问不到components中的注册的组件,拿到的是外部定义的test1,可以通过this.$options.components.xxx拿到components上的组件(当然直接拿到全局定义的组件的选项对象也能正确切换)。