Vuex使用过程演示
以vue-cli3新创建出来的项目为例,演示Vuex的使用过程。
创建项目:
1 2 3
   | vue create vuex-test cd vuex-test npm run serve
   | 
 
安装vuex:
进入项目的src/下新建一个文件store/index.js,并写入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
   |  import Vue from 'vue' import Vuex from 'vuex'
  Vue.use(Vuex)
  const store = new Vuex.Store({      state: {          count: 0     },     mutations: {          increment (state){             state.count++         }     } }) export default store 
 
  | 
 
进入main.js 注入store,使所有vue组件能够使用vuex :
1 2 3 4 5 6 7 8 9 10 11 12 13
   |  import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store'
  Vue.config.productionTip = false
  new Vue({   router,   store,   render: h => h(App) }).$mount('#app')
 
  | 
 
现在我们可以从组件的方法提交一个变更:
1 2 3 4 5 6
   | methods: {   increment() {     this.$store.commit('increment')      console.log(this.$store.state.count)   } }
  | 
 
在组件模板中使用状态:
1 2 3 4 5 6 7
   | {{ count }}
  computed: { 	count() { 		return this.$store.state.count 	} }
  | 
 
state状态的改变会触发computed的重新计算