Vuex的快速上手
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
},
getter: {
}
})
1. state
State 提供唯一的公共数据源,所有共享的数据都要统一放到 Store 的 State 中进行存储。
state { count:0 }
组件访问的两种方式
(1) this.$store.state.count
(2)
import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}
注意:Store 中的数据是不可以被直接操作的 ,所以我们需要mutations
2. mutations
mutations 用于变更 Store中 的数据。
mutations: {
add(state,step) {
// state即为上面的共享数据源state,下同
// step可选的第二参数
state.count++
}
}
组件中触发 mutations 的两种方式
(1)
methods: {
handle() {
this.$store.commit('add')
}
}
(2)
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['add'])
}
注意:在mutations中无法通过异步操作变更数据,必须通过actions
3. actions
actions 用于处理异步任务
actions:{
addAsync(context) {
setTimeout(()->{
context.commit('add')
},1000)
}
}
触发 actions 的两种方式
(1)
methods: {
handle() {
this.$store.dispatch('addAsync')
}
}
(2)
import { mapActions } from 'vuex'
methods: {
...mapActions(['addASync'])
}
4. getters
用于对 Store 中的数据进行加工处理形成新的数据
getter: {
showCount: state => {
return 'count='+state.count
}
}
使用的两种方式
(1) this.$store.getters.showCount
import { mapGetters } from 'vuex'
computed: {
...mapGetters(['showCount'])
}