2017-01-31 87 views
1

我有一個Vue應用程序,它有條件地顯示同一個組件的集合,我想綁定到創建或掛載的方法,但Vue不斷重複使用組件而不觸發這些方法。我試過將組件包裝在保持活動標籤中不起作用。不能阻止Vue JS(v2)重新使用組件

下面的代碼顯示了您對頁面的期望:將someVariable更改爲'test1'或'test2'顯示相關組件,但創建/裝載的方法最多隻觸發2次(例如,將某些變量更改爲' test1'記錄使用標籤type1創建和安裝1個組件,然後將其更改爲'test2'只記錄1個標籤類型爲3的組件。

目前使用V2.1.10

HTML

<div id="app"> 
    <div v-if="someVariable === 'test1'"> 
     <keep-alive> 
      <test-component data-type="type1"></test-component> 
     </keep-alive> 
    </div> 

    <div v-if="someVariable === 'test2'"> 
     <keep-alive> 
      <test-component data-type="type2"></test-component> 
     </keep-alive> 

     <keep-alive> 
      <test-component data-type="type3"></test-component> 
     </keep-alive> 
    </div> 
</div> 

JS/Vue公司

Vue.component('test-component', { 
    props: ['data-type'], 
    template: '<div><p>In the component: {{ dataType }}</p></div>', 
    created: function() { 
     console.log('component created: ', this.dataType); 
    }, 
    mounted: function() { 
     console.log('component mounted: ', this.dataType); 
    } 
}); 

var app = new Vue({ 
    el: '#app', 
    data: { 
     someVariable: "" 
    } 
}); 

回答

2

爲了您的具體的例子,從第二除去keep-alive是否應該做的伎倆https://jsfiddle.net/z11fe07p/464/

一個有趣的事情是,VUE似乎重新使用先前渲染的成分。因此,如果在第一個if中使用2個組件切換到下一個if時,它將重新使用一個組件,併爲該塊中的第二個組件創建一個新組件。當回到第一個if塊時,它將重新使用2個已經渲染的組件之一。

如上所述,觀察者更適合這種情況,因此可以在沒有完全控制的地方擺脫處理邏輯。您可以在文檔中看到此提示https://vuejs.org/v2/api/#updated

3

你應該在你的someVariable使用,而不是試圖鉤住created觀察者和mountedhooks

組件創建並在第一次可見(呈現)時安裝。沒有「顯示」或「隱藏」的鉤子。

https://vuejs.org/v2/guide/computed.html#Watchers

watch: { 
    someVariable: function (newValue) { 
    // test newValue and do what you have to do! 
    } 
}