Skip to content

动态组件&异步组件

动态组件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div id="root">
    <child-one v-if="type === 'child-one'"></child-one>
    <child-two v-if="type === 'child-two'"></child-two>
    <button @click="handleBtnClick">change</button>
</div>
<script>
    Vue.component('child-one', {
        template: `<div>child-one</div>`
    })
    Vue.component('child-two', {
        template: `<div>child-two</div>`
    })
    var vm = new Vue({
        el: "#root",
        data: {
            type: 'child-one'
        },
        methods: {
            handleBtnClick: function() {
                this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
            }
        }
    })
</script>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<div id="root">
    <component :is='type'></component>
    <button @click="handleBtnClick">change</button>
</div>
<script>
    Vue.component('child-one', {
        template: `<div>child-one</div>`
    })
    Vue.component('child-two', {
        template: `<div>child-two</div>`
    })
    var vm = new Vue({
        el: "#root",
        data: {
            type: 'child-one'
        },
        methods: {
            handleBtnClick: function() {
                this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
            }
        }
    })
</script>

v-once

提高静态内容展示效率

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div id="root">
    <child-one v-if="type === 'child-one'"></child-one>
    <child-two v-if="type === 'child-two'"></child-two>
    <button @click="handleBtnClick">change</button>
</div>
<script>
    Vue.component('child-one', {
        template: `<div v-once>child-one</div>`
    })
    Vue.component('child-two', {
        template: `<div v-once>child-two</div>`
    })
    var vm = new Vue({
        el: "#root",
        data: {
            type: 'child-one'
        },
        methods: {
            handleBtnClick: function() {
                this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
            }
        }
    })
</script>