欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue中 key keep-alive的實(shí)現(xiàn)原理

 更新時間:2018年09月18日 09:09:01   作者:麋鹿傳  
這篇文章主要介紹了Vue中 key keep-alive的實(shí)現(xiàn)原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

vue2.0提供了一個keep-alive組件用來緩存組件,避免多次加載相應(yīng)的組件,減少性能消耗

keep-aliv是Vue.js的一個內(nèi)置組件。它能夠不活動的組件實(shí)例保存在內(nèi)存中,而不是直接將其銷毀,它是一個抽象組件,不會被渲染到真實(shí)DOM中,也不會出現(xiàn)在父組件鏈中。

它有兩個生命周期:

  1. activated: keep-alive組件激活時調(diào)用
  2. deactivated: keep-alive組件停用時調(diào)用

它提供了include與exclude兩個屬性,允許組件有條件地進(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)識元素不再被復(fù)用,注意key是Vue中的一個保留的屬性,不能作為prop傳遞給子組件,否則會在控制臺看到Vue的報錯

但是keep-alive標(biāo)識不重復(fù)創(chuàng)建組件實(shí)例,也就是只會觸發(fā)一次created mounted事件,

利用兩者可以對組件的復(fù)用進(jìn)行比較精細(xì)的管理

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論