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本身被销毁,则缓存丢失。

作者:
...