vue2.0提供了一個(gè)keep-alive組件用來(lái)緩存組件,避免多次加載相應(yīng)的組件,減少性能消耗
keep-aliv是Vue.js的一個(gè)內(nèi)置組件。它能夠不活動(dòng)的組件實(shí)例保存在內(nèi)存中,而不是直接將其銷(xiāo)毀,它是一個(gè)抽象組件,不會(huì)被渲染到真實(shí)DOM中,也不會(huì)出現(xiàn)在父組件鏈中。
它有兩個(gè)生命周期:
它提供了include與exclude兩個(gè)屬性,允許組件有條件地進(jìn)行緩存。
keep-alive key
<!DOCTYPE html><html><head> <title></title> <script type="text/javascript" src="./vue.js"></script></head><body> <div id="app"> <keep-alive> <child-component key="1" v-if="seen" name="1"></child-component> <child-component key="2" v-if="!seen" name="2"></child-component> </keep-alive> <button @click="toggle">toggle</button> </div> <script type="text/javascript"> Vue.component('child-component', { template: `<input type="text" placeholder="enter">`, data() { return {} }, props: ["name"], mounted() { console.log(`${this.name} mounted`) } }) const vm = new Vue({ el: "#app", data: { seen: true }, methods: { toggle() { this.seen = !this.seen; } } }) </script></body></html>key是標(biāo)識(shí)元素不再被復(fù)用,注意key是Vue中的一個(gè)保留的屬性,不能作為prop傳遞給子組件,否則會(huì)在控制臺(tái)看到Vue的報(bào)錯(cuò)
但是keep-alive標(biāo)識(shí)不重復(fù)創(chuàng)建組件實(shí)例,也就是只會(huì)觸發(fā)一次created mounted事件,
利用兩者可以對(duì)組件的復(fù)用進(jìn)行比較精細(xì)的管理
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注