Vue 组件跳转数据保持方案

业务场景:从a组件跳转到b组件,再返回a组件,数据状态保持不变,比如表格的页数

1. 利用Vuex,保存需要缓存的组件的"组件名"
import Vue from 'vue'
import Vuex from 'vuex'

const state = {
  // 组件名单
  keepAlive: []
}

const mutations = {
  // 添加组件名
  SET_KEEPALIVE: (state, name) => {
    const index = state.keepAlive.indexOf(name)
    if (index === -1) {
      state.keepAlive.push(name)
    }
  },
  // 移除组件名
  REMOVE_KEEPALIVE: (state, name) => {
    const index = state.keepAlive.indexOf(name)
    if (index > -1) {
      state.keepAlive.splice(index, 1)
    }
  }
}

const actions = {
  // 添加组件名
  setKeepAlive({ commit }, name) {
    commit('SET_KEEPALIVE', name)
  },
  // 移除组件名
  removeKeepAlive({ commit }, name) {
    commit('REMOVE_KEEPALIVE', name)
  }
}
Vue.use(Vuex)
const store = new Vuex.Store({
  // 使用mapState、mapGetters等,需开启命名空间
  // namespaced: true,
  state,
  mutations,
  actions
}
export default store

// Vue实例配置store
new Vue({
  store,
}).$mount('#app')
2. 组件内调用beforeRouteEnter,beforeRouteLeave控制组件是否进行数据保持
export default {
  name: 'A',
  beforeRouteEnter(to, from, next) {
    // 指定那些组件返回到当前组件,移除当前缓存组件,以b组件为例,b组件返回到a组件时,移除组件名单中的a组件的组件名'A'
    if (from.path !== 'b组件路由路径') {
      // 第二个参数为需要被缓存的组件的"组件名",与上面name一致
      store.dispatch('removeKeepAlive', 'A')
      // store.dispatch('模块名/removeKeepAlive', 'A')
    }
    next()
  },
  beforeRouteLeave(to, from, next) {
  	// 指定跳转到那些组件时需要缓存组件,以b组件为例,跳转到b组件,组件名单添加a组件的组件名'A'
    if (to.path === 'b组件路由路径') {
      store.dispatch('setKeepAlive', 'A')
      // store.dispatch('模块名/setKeepAlive', 'SupplierAssessment')
    }
    next()
  },
 }
3. 使用缓存路由组件,让不展示的组件保持挂载不被销毁
<!-- 路由保持组件 -->
<!--
  this.$store.state.keepAlive:取出保存的组件名单
  对于使用了Vuex模块化的小伙伴,通过后面形式取组件名单:this.$store.state.模块名.keepAlive
-->
<keep-alive :include="this.$store.state.app.keepAlive">
  <!-- 找到路由组件展示位置 -->
  <router-view :key="key" />
</keep-alive>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值