vuex適用於開發大型單頁應用,這樣有利於我們管理更爲複雜的共享狀態
1、vuex的安裝
npm install vuex --save
在創建項目的時候,我們不能使用"vuex"來命名項目,npm安裝的包不能將自己作爲依賴進行安裝
2、在項目中的使用
2-1、創建一個store.js文件
//store
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)//在引入vuex之後,必須通過use方法調用纔可以使用
export default new Vuex.Store({
state: {//狀態管理的屬性
count: 0
},
mutations: {//要改變state的值,則必須通過提交mutations來實現
increment: function (state) {
state.count ++;
},
decrement: function (state) {
state.count --;
}
}
})
2-2、在main.js入口文件中如下使用
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store.js'//引入指定的狀態管理文件
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,//在vue對象中註冊之後纔可以使用
template: '<App/>',
components: { App }
})
2-3、在組件中的使用
computed: {
count: function () {
return this.$store.state.count
}
},
methods: {
increment: function () {
this.$store.commit('increment')//該處需要使用this.$store,同路由的使用this.$router
},
decrement: function () {
this.$store.commit('decrement')
}
}
將methods中的方法綁定在DOM上就可以觸發