javascript - Javascript - vuejs keep alive組件使用vif切換

問題

我有一個子組件,該子組件在v-if的頁面上不存在,在用戶單擊其他內容時保持緩存,以便在用戶返回失敗時,搜索詞再次顯示,無論我如何嘗試使用


Vue.component('child', {


 template: '<div>child: {{text}}<div>',


 data() {return {text:""}},


 created(){


 this.$nextTick(() => {


 this.text = `${Math.round(Math.random() * 100)}`


 })


},


 activated: function() {


 this.$nextTick(() => {


 	console.log('in activated');


 });


 }


})



var vm = new Vue({


 el: '#app',


 data: function() {


 return {


 showNow:false,


 message: 'This is a test.'


 }


 },


 methods: {


 changeText: function() {


 this.message = 'changed';


 },


 toggle() {


 this.showNow = !this.showNow


 }


 },


});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>


<div id="app">


 <keep-alive include="child">


 <div v-if="showNow">


 <h4>Title of section to be toggled</h4>


 <component is="child"></component>


 </div>


 </keep-alive>



 <button @click="toggle()">toggle child</button>


</div>

<keep-alive><child></child></keep-alive>或者使用

我不知道如何標記除Vue.js以外的內容,

时间: 原作者:

下面是經過輕微修改的代碼版本,keep-alive工作正常:


Vue.component('child', {


 template: '<div>child: {{text}}</div>',


 data() {return {text:""}},


 created(){


 console.log('in created')


 this.$nextTick(() => {


 this.text = `${Math.round(Math.random() * 100)}`


 })


 },


 activated: function() {


 this.$nextTick(() => {


 	console.log('in activated');


 });


 }


})



var vm = new Vue({


 el: '#app',


 data: function() {


 return {


 showNow:false,


 message: 'This is a test.'


 }


 },


 methods: {


 changeText: function() {


 this.message = 'changed';


 },


 toggle() {


 this.showNow = !this.showNow


 }


 },


});

<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>


<div id="app">


 <keep-alive>


 <child v-if="showNow"></child>


 </keep-alive>



 <button @click="toggle()">toggle child</button>


</div>

關鍵的改變是<child>必須是<keep-alive>的直接子級,此直接子級還必須是具有v-if的組件。

注意,created hook只第一次被調用,在後續激活時,調用activated hook而不是created

keep-alive的另一個常見錯誤是將v-if放在keep-alive組件本身或它祖先之上,這不能工作,因為keep-alive組件本身將被銷毀,keep-alive組件維護子組件的緩存,但是如果keep-alive本身被銷毀,則緩存丟失。

原作者:
...