VUEX以及辅助函数

1、vueX是干嘛的

vuex能够保存全局数据,供整个应用使用,可以在组件之间传递数据。

vuex保存的数据是响应式的

vuex保存的数据可以跟踪状态的变化

2、vueX的核心概念

state : 数据仓库 ,存储所有的 共享数据 ,相当于vue组件里的data

getter : 在state的基础上 派生的数据, 相当于vue组件里 computed

mutation:修改state的数据时,用mutation,这与跟踪状态 有关系

action:解决mutation里只能有同步代码的问题,action里可以有异步代码

3、vueX的数据流

组件里 dispatch(派发)vueX中的 action,action里commit(提交)mutation,mutation里修改state。state被修改后,会响应式到组件上。

扫描二维码关注公众号,回复: 15194932 查看本文章

4、辅助函数

现在的面试,都会问的比较多。而且在项目中大部分都会使用辅助函数来简化项目中的代码。

有了这些辅助函数后,在组件里,不用再写$store了。

mapState:把vuex中state(状态)映射(合并)到组件对象的computed上。直接使用计算属性就可以拿到vuex的状态

mapGetters:把vueX的getters映射到组件的computed上。

mapMutations:把vueX的mutations映射到组件的methods上。

mapActions: 把vueX的actions映射到组件的methods上。

示例代码

//1、vueX
export default new vueX.Store({
   state:{
       count:10
   }
})
 
//2、组件里
import { mapState } from "vuex";
 
export default {
  name: "Store01",
  data() {
    return {};
  },
  computed:{        
        ...mapState(['count']), //把vuex的state映射到组件的计算属性上
        a:function(){
            return 250;
        },
    }
};

5、modules

       当项目比较大时,所有的全局数据存放在state里,会非常混乱,怎么办?使用module,把数据分门别类的进行处理,即:模块化。 每个模块是一个独立的store。然后由总体的store引入所有的分模块store。

示例代码:

//1、moduleA.js  此模块里管理的数据是 count。
 
export default {
    namespaced:true, //这个命名空间是区分不同模块的
    state:{
        count:1
    },
    mutations:{
       ……………………
    },
    actions:{        
        incCount(context){
            console.log("moduleA的action");
            setTimeout(()=>{
                context.commit("incCount");
            },2000);
        }
    }
}
 
2、创建vueX.store对象
 
 
import moduleA from "./moduleA";
 
export default new vueX.Store({
    modules:{
        moduleA:moduleA
    }
    //简写:
    modules:{
        moduleA,moduleB
    }
});
 
 
//2、组件里派发action时,加上namespaced,用来区分不同的模块
 
this.$store.dispatch('moduleA/incCount');//moduleA就是模块名。保证派发的是moduleA里的incCount。
 

猜你喜欢

转载自blog.csdn.net/weixin_62247681/article/details/128281190