猿问

vue keep-alive同一个组件如何实现状态切换

路由配置


}, {

    path: '/submit',

    component: resolve => {

        require(['./pages/sb.vue'], resolve);

    },

    meta: {keepAlive: true}

}, {

app.vue配置


<!-- 这里是需要keepalive的 -->

<keep-alive>

    <router-view v-if="$route.meta.keepAlive"></router-view>

</keep-alive>


<!-- 这里不会被keepalive -->

<router-view v-if="!$route.meta.keepAlive"></router-view>

点击A页面的元素跳转到B页面,从B页面返回的时候可以保留A页面的历史记录和缓存。(上面配置可以实现)

但是,当从C页面点击进入A页面的时候不希望保留A页面的缓存和记录。请问如何动态的控制该页面的状态呢?


杨魅力
浏览 342回答 1
1回答

绝地无双

解决方案如下:step1vuex的store里面初始化值,如下操作:export default new Vuex.Store({&nbsp; &nbsp; state: {&nbsp; &nbsp; &nbsp; &nbsp; submitCache : true,&nbsp; &nbsp; &nbsp; &nbsp; vmRoute : '',step2main.js里面判断路由,修改字段值:router.afterEach(function(transition){&nbsp; &nbsp; //不缓存&nbsp; &nbsp; if ( (...) || (...)) {&nbsp; &nbsp; &nbsp; &nbsp; store.state.submitCache = false;&nbsp; &nbsp; }&nbsp; &nbsp; if(transition.path == '/xxx'){&nbsp; &nbsp; &nbsp; &nbsp; store.state.vmRoute = transition.path;&nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; store.state.vmRoute = '';&nbsp; &nbsp; }})step3app.vue如下修改,判断组件缓存逻辑:<keep-alive>&nbsp; &nbsp; <router-view v-if="isCache && vmRouter"></router-view></keep-alive><router-view v-if="!isCache || !vmRouter"></router-view>拿到所需字段:computed: {&nbsp; &nbsp; isCache : function(){&nbsp; &nbsp; &nbsp; &nbsp; return this.$store.state.submitCache;&nbsp; &nbsp; },&nbsp; &nbsp; vmRouter: function(){&nbsp; &nbsp; &nbsp; &nbsp; return this.$store.state.vmRoute;&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答