1. 程式人生 > 程式設計 >vue學習筆記之動態元件和v-once指令簡單示例

vue學習筆記之動態元件和v-once指令簡單示例

本文例項講述了vue動態元件和v-once指令。分享給大家供大家參考,具體如下:

點選按鈕時,自動切換兩個元件

<component :is="type"></component>,當點選按鈕之後,會自動清除原來的元件,顯示新的元件。

每一次切換,都需要銷燬+建立

但是這樣消耗有點大,所以我們在子元件中引用了v-once指令,這樣可以將顯示在頁面中的元件存到記憶體中,不會完全銷燬。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>動態元件和v-once指令</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <component :is="type"></component>
<!--  <child-one v-if="type === 'child-one'"></child-one>-->
<!--  <child-two v-if="type === 'child-two'"></child-two>-->
  <button @click="handleBtnClick">change</button>
</div>
</body>
</html>
<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: '#app',data: {
      type: 'child-one'
    },methods: {
      handleBtnClick: function () {
        this.type = (this.type === 'child-one' ? 'child-two' : 'child-one');
      }
    }
  })
</script>

執行結果:

vue學習筆記之動態元件和v-once指令簡單示例

vue學習筆記之動態元件和v-once指令簡單示例

感興趣的朋友可以使用線上HTML/CSS/JavaScript程式碼執行工具:http://tools.jb51.net/code/HtmlJsRun測試上述程式碼執行效果。

希望本文所述對大家vue.js程式設計有所幫助。