上一章Vuex的基本使用
Vuex中的主要核心概念
- State
- Mutation
- Action
- Getter
State
- State提供唯一的公共数据源,所有共享的数据都要统一放到Store的State中进行存储。
const state = {
count:"0"
};
- 组件访问State中数据的第一种方式
this.$store.state.全局数据名称
- 组件访问State中数据的第二种方式
//1,从vuex中按需导入mapState函数
import { mapState} from 'vuex'
通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
//2,将当前组件需要的全局数据,映射为当前组件的computed计算属性
computed:{
...mapState(['count'])
}
Mutation
- Mutation用于变更Store中的数据
- 只能通过Mutation变更Store中的数据,不可以直接操作Store中的数据
- 通过这种方式虽然操作起来稍微繁琐一下,但是可以集中监控所有数据的变化
//定义mutations
const mutations = {
add(state) {
//变更状态
state.count++;
},
};
//触发mutations
methods: {
Add1() {
this.$store.commit('add')
},
},
- 可以触发mutations 时传递参数
const mutations = {
addN(state, val) {
//变更状态
state.count += val;
},
};
methods: {
AddN() {
this.$store.commit('addN',5)
},
},
- this.$store.commit()是触发mutations 的第一种方式,触发mutations 的第二种方式
//1,从vuex中按需导入mapMutations 函数
import { mapMutations } from 'vuex'
通过刚才导入的mapMutations 函数,将需要的mutations 函数,映射为当前组件的methods方法
methods: {
...mapMutations(['add','addN'])
},
- 在mutations 不能写异步操作
Action
- Action用于处理异步任务
- 如果通过异步操作变更数据,必须通过Action,而不能使用Mutation,但是在Action中还是要通过触发Mutation的方式间接变更数据
//定义Action
const mutations = {
add(state) {
//变更状态
state.count++;
},
};
const actions = {
addAsync(mutations) {
setTimeout(() => {
mutations.commit("add");
}, 1000);
},
};
//触发Action
methods: {
// 异步自增
btnHandler3() {
this.$store.dispatch("addAsync");
},
},
- 触发actions 异步任务时携带参数
//定义Action
const mutations = {
addN(state, val) {
state.count += val;
},
};
const actions = {
addNAsync(mutations,val) {
setTimeout(() => {
mutations.commit("addN",val);
}, 1000);
},
};
//触发Action
methods: {
btnHandler4() {
this.$store.dispatch("addNAsync", 5);
},
},
- this.$store.dispatch()是触发actions 的第一种方式,触发actions 的第二种方式
//1,从vuex中按需导入mapActions 函数
import { mapActions } from 'vuex'
通过刚才导入的mapActions 函数,将需要的actions 函数,映射为当前组件的methods方法
methods: {
...mapActions (['addAsync','addNAsync'])
},
Getter
- Getter用于对Store中的数据进行加工处理形成的新数据
- Getter可以对Store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
- Store中数据发生变化,Getter的数据也会跟着变化
//定义Getter
const state = {
count: 0,
};
const getters = {
showNum(state) {
return "当前最新的数量是【" + state.count + "】";
},
};
- 使用getters 的第一种方式
this.$store.getters.名称
- 使用getters 的第二种方式
import { mapGetters } from 'vuex'
computed: {
...mapGetters (['showNum'])
},
最后附上简单的Vuex工程:vuex