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>

猜你喜欢

转载自blog.csdn.net/qq_45158026/article/details/128727914
今日推荐