栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > Vue.js

关于路由和Vuex擦出的那点火花

Vue.js 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于路由和Vuex擦出的那点火花

这是本人在用vue做项目的一些经验,以此作为日常记录
第一小段:

1.问题:

route + vuex,在项目中遇到的是不同页面之间相互跳转,route会刷新数据,但是vuex不能记录最新的数值的问题;

2.解决方法:

主要是通过mapState(+必要时采取localStorage或者sessionStorage保存一个键值)来获取最新的属性,之后通过dispatch来分发action方法从而commit mutation 最后改变state的属性值(这是最基本的连环操作,哈哈);

3.还是直接上代码吧:简单,明了和复用

案例1.商品列表
 store 中:
// actions
const actions = {
    changeParam({commit},params){  //  修改参数
 commit(types.GET_NEW_PARAM,{ params });
    },
    getAllProducts({commit,state}){ // 获取所有车位列表
 axios.post(proApi.api.commonListApi,state.goodParam)
   .then((response)=>{
     Util.processRes(response,(responseData)=>{
   let products = responseData.data;
  commit(types.GET_GOODS_LIST,{ products })
     },(responseData)=>{
// todo
     })
 });
    }
}

// mutations
const mutations = {
    [types.GET_GOODS_LIST](state,{ products }){
 state.goodList = products;
    },
    [types.GET_NEW_PARAM](state,{ params }){
 for (var i in   state.goodParam) {
   for (var j in params) {
     if (i == j) {
state.goodParam[i] = params[j];
     }
   }
 }
     }
  }
// 以上是strore中主要的点

在单文件.vue中处理

 mounted(){
      this.navTabIndex;  // 注意需要在首先渲染,否则没有实际的作用
    },
  computed:{
      ...mapState({
   "navTabIndex": function(state){ // 箭头函数会有this的问题
let nowRoute = this.$route.name;  // 当前路由 
this.switchPage(nowRoute);  // 根据路由修改请求参数
this.$store.dispatch('changeParam', this.param); // 同步操作
return state.goods.goodParam;  // 在计算属性中,返回最新请求参数
     }
      }),
    }
// 监听路由变化
    watch:{
 $route(val){
   this.switchPage(val.name); // 一个switch选择语句,判断当前路由,然后修该.vue中的this.param 请求参数
   this.$store.dispatch('changeParam',this.param);
   this.$store.dispatch('getAllProducts');
 },
      },
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/241690.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号