一、安装vuex
npm install vuex --save
二、创建store
在项目src目录下创建store目录,在store目录中创建index.js文件。写入一下内容:
import Vue from 'vue'
import Vuex from 'vuex'
// 挂在Vuex
Vue.use(Vuex)
// 创建Vuex对象
const store = new Vuex.Store({
state:{
// 存放的键值对就是所要管理的状态
// 以key:value为例
key : value,
},
mutations:{
setKey(state, payload) {
state.key = payload;
}
}
})
export default store
三、挂载store
在main.js中,添加代码:
···
import store from './store'
···
new Vue({
el: '#app',
router,
store: store, //store:store 和 router一样,将我们创建的Vuex实例挂载到这个vue实例中
components: { App },
template: '<App/>'
})
四、在组件中使用
将需要使用的值写在computed中:
computed:{
key() {
return this.$store.state.key;
}
}
如果在组件中使用v-model绑定computed中的值,需要在computed中定义set方法,如下:
computed:{
key:{
get(){
return this.$store.state.key;
},
set(val){
this.$store.commit('setKey', val);
}
}
}