Vue 中的動態元件與 v-once 指令
阿新 • • 發佈:2018-11-05
toggle 兩個元件的功能,程式碼如下。
<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>child1</div>' }) Vue.component("child-two",{ template: '<div>child2</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>
除了上述的方法,我們還可以通過編寫動態元件的方法實現。上面的方法,每次都要銷燬一個再建立一個元件,挺耗費效能的。
動態元件
使用component 標籤,該標籤的繫結屬性 is 則指它實際上是哪個元件。
程式碼如下。
<div id="root"> <component :is="type"></component> <button @click="handleBtnClick">change</button> </div> <script> Vue.component("child-one",{ template: '<div>child1</div>' }) Vue.component("child-two",{ template: '<div>child2</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 指令,使用如下。該指令會使dom 第一次展示的時候,放入記憶體裡,以後使用的時候讀出記憶體即可。可以提高一些靜態內容的展示效率。
<div id="root"> <!-- <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> <!-- v-once --> <script> Vue.component("child-one",{ template: '<div v-once>child1</div>' }) Vue.component("child-two",{ template: '<div >child2</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>