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上就可以触发