vuex属性
state
Vuex 使用单一状态树,即每个应用将仅仅包含一个store 实例,但单一状态树和模块化并不冲突。存放的数据状态,不可以直接修改里面的数据。
mutations
mutations定义的方法动态修改Vuex 的 store 中的状态或数据。
action
actions可以理解为通过将mutations里面处里数据的方法变成可异步的处理数据的方法,简单的说就是异步操作数据。view 层通过 store.dispath 来分发 action。
getters
类似vue的计算属性,主要用来过滤一些数据。
modules
项目特别复杂的时候,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。
vuex方法
发送数据
dispatch:异步操作,写法this.store.dispatch(‘mutations方法名’,值)
commit:同步操作,写法:this.store.commit(‘mutations方法名’,值)
获取数据
this.$store.state.xxxx
vuex辅助函数
辅助函数:mapState、mapGetters、mapActions、mapMutations
export default new Vuex.Store({
state: {
title:'ping',
pkey:'02609',
nickName:'tekeMe',
firstname:'Chen',
lastname:'father',
age:20,
gender:'男',
money:16K
},
realname(state){
return state.firstname+state.lastname
},
money_us(state){
return (state.money/7).toFixed(2)
}
mutations: {
[ADD_AGE](state,payLoad){
state.age+=payLoad.number
}},
actions: {
getUserInfo(){
return {
nickname:'Chen',
age:20
}
}},
modules: {}
})
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import {mapState, mapGetters, mapActions, mapMutations} from 'vuex'
export default {
name: 'index',
computed: {
...mapState(['title','pkey','nickName'])
...mapGetters(['realname','money_us'])
},
methods:{
...mapMutations([ADD_AGE])
..mapActions(['getUserInfo'])
}
}