vuex基础用例
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const state = {
count:0
},
const mutations = {
add(state){
state.count++
},
dcre(state){
state.count--
},
}
const actions = {
add:({ commit }) => {
commit("add")
},
dcre:({ commit }) => {
commit("dcre")
}
},
export default new Vuex.Store({
state,
mutations,
actions
});
关于actions:
官方文档是这么写的:
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
然后在组件中导入, 通过Action触发add、dcre方法
<template>
<div>
{
{ $store.state.count }}
<button @click="add">增加</button>
<button @click="drce">删减</button>
</div>