vue基础之动态组件

动态组件用于频繁切换组件

(1)刚开始

<body>
    <div id="root">
        <child-one v-if="type === 'child-one'"></child-one>
        <child-two v-if="type === 'child-two'"></child-two>
        <button @click="change">change</button>
    </div>
    <script>
        //创建子组件
        Vue.component('child-one', {
            template: `<div>
                            child-one
                       </div>`
        })
        Vue.component('child-two', {
            template: `<div>
                            child-two
                       </div>`
        })

        //创建vue实例对象
        var vm = new Vue({
            el: '#root',
            data: {
                type: 'child-one'
            },
            methods: {
                change() {
                    this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
                }
            }
        })
    </script>
</body>

改进后

<div id="root">
        <component :is="type"></component>
        <button @click="change">change</button>
    </div>
 //创建子组件
        Vue.component('child-one', {
            template: `<div v-once>
                            child-one
                       </div>`
        })
        Vue.component('child-two', {
            template: `<div v-once>
                            child-two
                       </div>`
        })

猜你喜欢

转载自blog.csdn.net/qq_45549336/article/details/106710914