vuex使用:
state中定义数据:
const state = {number : 1}
getter中写获取值的方法
const getter = {
getFunction(state){
return state.number = ??
}
}
页面中取值:$store.getters.getFuntion
actions类比view层,用于对state中的数据进行操作,actions中定义方法increment,再去调用
mutation中的方法inc:
this.$store.dispatch(‘increment’) //调用action中的方法
actions中定义方法:
const actions = {
increment({commit,state}){
//处理业务逻辑
//处理业务逻辑结束
commit('inc')
}
}
mutations类比dao层,最中修改state中的数据:
const mutations = {
inc(state){
state.number++
}
}
简化版:mapState、mapGetters、mapActions
先引入:import {mapState,mapGetters,mapActions} from ‘vuex’
计算属性中取数据:
computed:{
…mapState([‘number’]) //取state中的number
…mapGetter([‘getFunction’])
}
调用actions:
methods:{
…mapActions([‘increment’]) //页面中方法要与此一致,即可调用到action中的increment()
}