下载
npm install vuex --save
使用
- 新建一个文件夹(
javascript
) - 新建一个文件(
store.js
)
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increase(state) {
state.count++
},
subtract(state){
state.count--
}
},
// 注册一个简单的 action
actions: {
actionIncrease({
commit
}) {
commit('increase')
},
actionSubtract({
commit
}) {
commit('subtract')
}
}
})
export default store
main.js
import store from "./javascript/store"; //引入store
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store, //加入store对象
components: {
App
},
template: '<App/>'
})
vue
<template>
<div id="vuex">
<button @click="subtract">-</button>
{{count}}
<button @click="add">+</button>
</div>
</template>
<script>
export default {
data() {
return {
// count:store.state.count
};
},
computed: {
count() {
return this.$store.state.count;
}
},
methods: {
// 分发 Action
add() {
this.$store.dispatch('actionIncrease')
},
subtract() {
this.$store.dispatch('actionSubtract')
}
}
};
</script>