Demo 通过点击button,实现两个组件的切换,除了使用v-if,还可使用:is 动态组件来完成
我觉得他可以用在根据不同的角色展示不同组件上使用
通过:is属性绑定data中的type,type为一个组件的name,这样,进入页面就会默认展示一个组件,通过点击改动data中type中的name,实现组件切换
<div id="app"><component :is="type"></component> // vue定义的标签<button @click="handleClick">切换</button>
</div>
<script>Vue.component('containerOne', {template: `<div>组件1</div>`,})Vue.component('containerTwo', {template: `<div>组件2</div>`,})var vm = new Vue({el: '#app',data: {type: 'containerOne'},methods: {handleClick() {this.type = this.type == 'containerOne' ? 'containerTwo' : 'containerOne'}}})
</script>
复制代码