1、Vuex目录结构
讲解这些属性之前,我们先看项目的store目录结构和主要代码:
app/index/store/index.js代码:
import Vue from "vue";
import Vuex from "vuex";
import mutations from "./mutations";
import actions from "./actions";
Vue.use(Vuex);
const state = {
userInfo: null,
role: "",
currentSearch: {}
};
export default new Vuex.Store({
state,
actions,
mutations,
modules: {}
});
app/index/store/mutation-type.js代码:
export const SET_USER_INFO = "SET_USER_INFO";
export const SET_ROLE = "SET_ROLE";
export const SET_CURRENT_SEARCH = "SET_CURRENT_SEARCH";
app/index/store/mutation.js代码:
import * as types from "./mutation-types";
export default {
[types.SET_USER_INFO](state, userInfo) {
state.userInfo = userInfo;
},
[types.SET_ROLE](state, role) {
state.role = role;
},
[types.SET_CURRENT_SEARCH](state, currentSearch) {
state.currentSearch = currentSearch;
}
};
2、vuex的映射语法
3、mapSate使用
(1)之前的写法
computed: {
userInfo () {
return this.$store.state.userInfo;
},
role () {
return this.$store.state.role;
},
currentSearch () {
return this.$store.state.currentSearch;
}
}
(2)使用mapState
数组形式:想用哪一个数据,直接使用...mapState 映射出哪一个数据就好:
import { mapState } from "vuex";
computed: {
...mapState([
"userInfo"
"role",
"currentSearch"
])
}
对象形式:以对象的形式映射进来,可以在自己的组件中起一个别名,template页面可直接使用 a 进行渲染:
import { mapState } from "vuex";
computed: {
...mapState({
userInfo: state => state.userInfo,
role: state => state.role,
a: state => state.currentSearch
})
}
如上代码,我们使用 mapState工具函数会将store中的state映射到局部计算属性中。我们在mounted方法内,直接使用 this.xx即可使用到对应computed中对应的属性了。也就是我们使用 this.userInfo就直接映射到 this.$store.state.userInfo了。
<template>
<div>{{ role }}</div>
<template>
<script>
export default {
mounted() {
console.log(this.userInfo);
}
}
</script>
4、mapMutations使用
(1)之前的写法
methods: {
setCurrentSearch() {
this.$store.commit('SET_CURRENT_SEARCH', "笔记本");
}
}
(2)使用mapMutations
数组形式:
import { mapMutations } from "vuex";
methods: {
...mapMutations([
"SET_USER_INFO",
"SET_ROLE",
"SET_CURRENT_SEARCH"
])
}
对象形式:
import { mapMutations } from "vuex";
methods: {
...mapMutations({
"SET_USER_INFO": "SET_USER_INFO",
"SET_ROLE": "SET_ROLE",
"SET_CURRENT_SEARCH": "SET_CURRENT_SEARCH"
})
}
在 methods 的别的方法里面可以直接 this.xx来调用,就等价于 commit 在提交它,也就是我们使用 this.SET_CURRENT_SEARCH("笔记本")就直接映射到this.$store.commit('SET_CURRENT_SEARCH', "笔记本"):
methods: {
setCurrentSearch() {
this.SET_CURRENT_SEARCH("笔记本");
}
}
5、mapActions使用
(1)之前的写法
methods: {
setCurrentInfo() {
this.$store.dispatch('SET_CURRENT_INFO', "xxx");
}
}
(2)使用mapActions
数组形式:
import { mapActions } from "vuex";
methods: {
...mapActions([
"SET_CURRENT_INFO"
])
}
对象形式:
import { mapActions } from "vuex";
methods: {
...mapActions({
"SET_CURRENT_INFO": "SET_CURRENT_INFO"
})
}
在 methods 的别的方法里面可以直接 this.xx来调用,就等价于dispatch在提交它,也就是我们使用 this.SET_CURRENT_INFO("xxx")就直接映射到this.$store.dispatch('SET_CURRENT_INFO', "xxx"):
methods: {
setCurrentInfo() {
this.SET_CURRENT_INFO("xxx");
}
}