动态组件

切换两个不同组件

  • 方法1
    使用 v-if 和按钮点击切换
// js Vue.component('child-one',{ template:`
child-one
` }); Vue.component('child-two',{ template:`
child-two
` }); var vm = new Vue({ el:'#app', data:{ type:'child-one' }, methods:{ change:function(){ this.type = (this.type == 'child-one' ? 'child-two' : 'child-one') } } });

  • 方法2
    使用动态组件 :is 和按钮切换
// js 与方法1 相同

根据:is 后面的属性值,显示相应的组件。


最后,因为频繁切换两个组件,vue每次都是要先销毁一个,在创建另一个。这里建议加上 v-once 指令。

Vue.component('child-one',{
    template:`
        
child-one
` });

v-once 官方 API 解释:
只渲染元素和组件一次。随后的重新渲染,元素/组件及其所有的子节点将被视为静态内容并跳过。这可以用于优化更新性能。

你可能感兴趣的:(动态组件)