我有一個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: ""
}
});