动态组件与v-once指令

使用v-once指令提高静态内容展示效率,减少频繁创建和销毁dom的操作;

<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>动态组件与v-once指令</title>
  <script src='./vue.js'></script>
</head>

<body>
  <div id="app">
    <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: '#app',
      data: {
        type: 'child-one'
      },
      methods: {
        handleBtnClick: function() {
          this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
        }
      }
    })
  </script>
</body>

</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>动态组件与v-once指令</title>
  <script src='./vue.js'></script>
</head>

<body>
  <div id="app">
    <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: '#app',
      data: {
        type: 'child-one'
      },
      methods: {
        handleBtnClick: function() {
          this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
        }
      }
    })
  </script>
</body>

</html>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>动态组件与v-once指令</title>
  <script src='./vue.js'></script>
</head>

<body>
  <div id="app">
    <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>
    // 使用v-once指令提高静态内容展示效率,减少频繁创建和销毁dom的操作
    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: '#app',
      data: {
        type: 'child-one'
      },
      methods: {
        handleBtnClick: function() {
          this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
        }
      }
    })
  </script>
</body>

</html>

推荐阅读更多精彩内容