npm install -g @vue/cli
vue create my-project
npm install vuex --save
import Vue from 'vue'
import Vuex from 'vuex'
import App from './App.vue'
//main.js
Vue.use(Vuex)
Vue.config.productionTip = false
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++
}
}
});
store.commit('increment');
window.console.log(store.state.count);
new Vue({
render: h => h(App),
}).$mount('#app')
上面改为:
// App.vue
<template>
<div id="app">
{{ count }}<br/>
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
name: 'App',
computed: {
count () {
return this.$store.state.count;
}
},
methods: {
increment () {
// return this.$store.commit('increment');
return this.$store.dispatch('increment');
}
}
}
</script>
// main.js
import Vue from 'vue'
import Vuex from 'vuex';
import App from './App.vue'
Vue.use(Vuex);
Vue.config.productionTip = false
const store = new Vuex.Store({
state: {
count: 0
},
mutations: {
increment (state) {
state.count++;
}
},
actions: {
increment ({commit}) {
setTimeout(() => {
commit('increment');
}, 1000);
}
}
})
new Vue({
store,
render: h => h(App),
}).$mount('#app')