Vuex的基本使用
安装:
npm install vuex --save
vue add vuex
使用:
在store/index.js中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: { //声明同步的方法
increment (state) {
state.count++
}
},
action:{ //声明异步的方法
}
})
通过 store.state 来获取状态对象,以及通过 store.commit 方法触发状态变更:
store.commit('increment')
console.log(this.$store.state.count) // -> 1
通过组件的方法变更store里面的状态:
第一步:添加改变store状态的点击事件:
<el-button type="success" @click="handleAddCount">加1</el-button>
第二步:再点击事件中通过dispatch触发store文件夹下的index.js中actions中声明的方法
<script>
export default {
methods: {
handleAddCount(){
this.$store.dispatch('increment') //increment 是store/index.js中actions中声明的方法
}
}
}
</script>
第三步: 1、在action 中声明dispatch中的方法,通过commit提交mutations中声明的方法;
2、在mutations中声明方法,并且修改状态
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: { //当前的状态
count: 0
},
mutations: { //声明同步的方法
addCount(stare){
stare.count++;
}
},
actions: { //声明异步的方法
increment({commit}){ //声明方法
commit('addCount') //通过commit提交mutations中声明的方法 ,'addCount'是mutations中声明的放发
}
},
modules: {
}
})
浙公网安备 33010602011771号