1、安装
npm install vuex@next --save
yarn add vuex@next --save
2、搭建store
在vue项目main.js中挂载
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from "@/store/deviceProps";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
在 src 目录下新建 store 文件夹,在 store 文件夹内新建一个deviceProps.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
//类似于vue中的data,是唯一数据源,是一个对象
state: {
data: {
powerstate: 0,
}
},
// 和vue中的计算属性类似,state中的数据发生变化时,它就会触发
// 并且会自动保存修改了的内容
getters:{
getData(state) {
return state.data
}
},
// 更改state中状态的逻辑,主要是写一些同步操作的方法
mutations: {
addData(state, person) {
state.data = {
...state.data,
...person,
}
}
},
// 提交mutation,区别在于可以异步操作
actions:{},
// 将store分割成模块
modules:{}
})
export default store
3、在组件中获取state
export default {
name: "test_1",
data() {
return {
a: {}
}
},
watch: {
'$store.state.data': {
deep: true,//对象需深度监听
handler: function (newVal) {
this.a = newVal;
}
}
},
mounted() {
this.a = this.$store.getters.getData // 通过getters访问
}
}
4、页面中提交数据给state
使用commit()可将deviceProps数据传递给addData
this.$store.commit('addData', this.deviceProps);