Vuex 状态管理 1 State 三种状态用法
A.直接获取Store中的State 属性的值
Computed:{ // 计算属性
Count (){
Return This.$Store.State.Count
}
}
b.直接从mapState中获取
computed:{
...mapState(['count']) <===> 等同上面的直接获取store中state中的属性值
}
c.在mapState中定义别名
computed:{
...mapState({
count:(state) = state.count
})
}
以上三种都可以获取当前state中对应的参数值 注意在引用之前我们必须需要引入
import {mapState,mapGetters,mapMutations} from 'vuex'
2 getter 获取计算后的state 属性的值 // getter 只是针对的是state里面的参数
列如 从store的getters中获取到firstNmme 和 lastName 属性 在getter中展示
fullName (state) {
return `${state.firstName}+${state.lastName}`
}
computed :{
fullName () {
return this.$store.getters.fullName
}
}
mapGetters 中获取
computed:{
...mapGetters(['fullName'])
}
3 mutation 更改state
updateCount (state,{num}) {
state.count = num
}
使用store 的commit 触发mutation
mounted (){
setInterval(()=>{
this.$store.commit('updateCount',{num:num++})
},1000)
}
使用mapMutations
methods:{
...mapMutations(['updateCount'])
}
此时ubdateCount的用法
mounted(){
setInterval (()=>{
this.updateCount ({num:num++})
},1000)
}
使用mapMutations 的说法
methods:{
...mapMutations(['ubdateCount'])
}
4 action异步修改state
// action.js
updateCountAsync (store, data) {
setTimeout(() => {
store.commit('updateCount', {num: data.num})
}, data.time)
}
使用store的dispatch 触发action
mounted (){
this.$store.dispatch('updateCountAsync',{num:3,time:2000})
}
使用mapActions methods:{
...mapActions(['updateCountAsync]);
}
此时updateCountAsync的用法
mounted () {
this.updateCountAsync({
num: 3,
time: 2000
})
}
5 可以直接引入stroe.js 中导入
import Vuex from 'vuex'
import defaultState from './state/state'
import mutations from './mutations/mutations'
import getters from './getters/getters'
import actions from './action/action'
const isDev = process.env.NODE_ENV === 'development'
export default () => {
return new Vuex.Store({
strict: isDev,
state: defaultState,
mutations,
getters,
actions
})
}