activated生命周期 和vuex的模块化示例

背景:

新需求:组件用keep-alive缓存的时候,不同页面跳转过来,需要判断走不走数据请求

但是要知道keep-alive 这种情况下路由跳转,生命周期mounted 是不触发的。

解决方法:

要换成activated生命周期。

 

思路是:data设置一个字段(比如prevCityId) 状态管理存储之前的id
然后如果是当前的state存储的值和新设置的字段的值是相等的,return出去,后续就不执行了。

如果不一样,那么正常请求数据


 data() {
    return {
      
      prevCityId: -1,
    };
--------------


activated() {   
var cityId = this.$store.state.city.id; if (this.prevCityId === cityId) { return; } this.isLoading =true; console.log(123); var url = `xxxx/gateway?cityId=${cityId}&pageNum=1xxxx`; this.$axios({ url, 。。。。
}).then((res) => {
      var msg = res.data.msg;
        if(msg==='ok'){
        xxxxx
       this.prevCityId = cityId;
      }

}


关于store的模块化

在store下面创建一个文件夹(比如city),下面放index.js


在store下的index.js 引入他 ,然后引入声明他的子状态

import Vue from 'vue'
import Vuex from 'vuex'
import city from './city'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
    city
  }
})


city 下的index.js写法

const state = {
    nm:window.localStorage.getItem('nowNm')||'北京',
    id: window.localStorage.getItem('nowId')||1
};
const actions = {

};
const mutations = {
    //commit方法的接收函数,第一个参数为state,第二个参数为穿过来的对象
    CITY_INFO(state,payload){  //方法名为大写,表示为一个状态管理方法
        state.nm = payload.nm;
        state.id = payload.id;
    }
};

export default { 
    namespaced :true,//namespaced: true 的方式使其成为带命名空间的模块。保证在变量名一样的时候,添加一个父级名拼接。
    state,
    actions,
    mutations
}







原文地址:https://www.cnblogs.com/zhuangdd/p/14646203.html