vue中的动态组件

在我们平时使用vue中的模板的时候,许多时候都是直接定义成一个固定的模板,但是,vue中提供了一个动态模板,可以在任意模板中切换,就是用vue中<component>用:is来挂载不同的组件。


<div id="app" v-cloak>
        <component :is="currentView"></component>
        <button @click="handleChangeView('A')">A</button>
        <button @click="handleChangeView('B')">B</button>
        <button @click="handleChangeView('C')">C</button>
</div>
<script>
        var app = new Vue({
            el: '#app',
            components:{
                comA:{
                    template:`
                        <div>组件A</div>
                    `
                },
                comB:{
                    template:`
                        <div>组件B</div>
                    `
                },
                comC:{
                    template:`
                        <div>组件C</div>
                    `
                }
            },
            data:{
                currentView:'comA'
            },
            methods:{
                handleChangeView:function(component){
                    this.currentView='com'+component;
                }
            }
        });
</script>
我们在components中注册了三个模板,当我们点击当前按钮的时候,就会将模板切换模板,可以说是非常方便了。

猜你喜欢

转载自blog.csdn.net/qq_36529459/article/details/79573040