Vue学习第三天天之VueX

说明

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

通过在根实例中注册 store 选项,该 store 实例会注入到根组件下的所有子组件中,且子组件能通过 this.$store 访问到。

1.state 状态,每个应用只能有一个state,可以看成是静态属性,不改变的。

2.getters store的计算属性

3.mutations 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,mutation中的事件有两个参数(state,payload),mutation不处理异步操作。子组件通过this.$store.commit触发其事件

4.actions 

Action 提交的是 mutation,而不是直接变更状态,Action 可以包含任意异步操作。

事件也支持两个参数(context,payload),其中context具有和store实例相同的方法,可以通过contex.commit提交一个mutation

子组件通过this.$store.dispatch触发其事件。

5.modules 包含上面四个部分,一个应用可以右多个模块

例子

store:

mutations: {
add (state , n ) {
state.count += n;
},
minus (state) {
state.count--;
}
},
actions : {
addhelper(context,payload){
$.get("api.txt",function(data){
context.commit('add',Number(data));
});
}
},

component:

methods : {
addhandler(){
this.$store.dispatch("addhelper");
},
minusnandler(){
this.$store.commit("minus");
}
posted @ 2020-08-11 11:28  OnceKing1996  阅读(85)  评论(0编辑  收藏  举报