vuex的五大属性
1:state 基本数据,存储变量
const store = new Vuex.Store({
state: {
a: 'true',
b: 2,
c: false,
d: null
},
});
使用方法
<span>{{数据名字}}<span>
import [Mapstate] from vuex
export default{
computed:{
...Mapstate['数据名字']
}
}
this.$store.state.a
2:getter state的计算属性
2. getter:从基本数据(state)派生的数据,相当于state的计算属性,具有返回值的方法
getter: {
a: state => state.a,
b: function(state){
return state.b * 2
}
}
使用方法
<span>{{'函数名'}}</span>
import {mapGetters} from vuex;
export default{
computed:{
...mapGetters['函数名']
}
}
this.$store.getters.a
3:mutation 更改state中状态的逻辑 同步操作(唯一可以修改state中值的地方)
## 3.mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。
mutations: {
a: (state, userId) => {
state.userId = userId
},
b: (state, token) => {
// console.log(token)
state.token = token
}
},
使用方法
this.$store.commit('mutation中的函数',传递的值)
方法二
import {mapMutation} from vuex
export default{
methods:{
...mapMutation['函数名]//可以作为函数直接调用
fn(){
this.函数名()
}
}
}
4: action:和mutation的功能大致相同,不同之处在于 1) Action 提交的是 mutation,而不是直接变更状态。 2) Action 可以包含任意异步操作。
actions: { // {} 是es6中解构,把对象解构成属性
a({ commit }, value) {
commit('SET_USER', value)
},
}
使用方法
this.$store.dispatch('函数名',值)
5:modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理如下图