Vuex.store对象
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state, n) {
state.count += n
}
},
actions:{
incrementAsync(context) {
setTimeout(()=>{
context.commit('increment')
})
}
}
})
state存放数据
1.组件中访问this.$store.state.数据名
2.导入import {mapState} from ‘vuex'
组件computed:{ ...mapState(['数据名']) }
getters包装数据
1.this.$store.getters('getter名')
2.导入import {mapGetters} from ‘vuex'
组件computed:{ ...mapActions(['函数名']) }
mutations操作数据
集中管理
不能存在异步操作
1.组件中调用this.$store.commit(‘函数名’)
2.导入import {mapMutations} from ‘vuex'
组件methods:{ ...mapMutations(['函数名']) }
actions异步操作
不能直接操作state中的数据
Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters
1.this.$store.dispatch('action名')
2.导入import {mapActions} from ‘vuex'
组件methods:{ ...mapActions(['函数名']) }