vue

Vue学习笔记(十五)之动态组件与v-once指令

Posted by weite122 on 2018-09-09

v-if实现组件切换

  • 效果
  • 代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>动态组件和v-once指令</title>
    <script src="http://vuejs.org/js/vue.js"></script>
    </head>
    <body>
    <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>
    </body>
    </html>

动态组件实现组件切换

  • 效果
  • 代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>动态组件和v-once指令</title>
    <script src="http://vuejs.org/js/vue.js"></script>
    </head>
    <body>
    <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>
    </body>
    </html>

v-once优化性能

  • 将代码这部分修改为一下即可:
    1
    2
    3
    4
    5
    6
    7
    Vue.component('child-one', {
    template: '<div v-once>child-one</div>'
    })

    Vue.component('child-two', {
    template: '<div v-once>child-two</div>'
    })