1.引入store
安裝引入vuex,在main.js里面:
import store from './store' //+++
new Vue({
el: '#app',
router,
store, //+++
components: { App },
template: '<App/>'
})
在store文件夾下創建index.js入口文件,添加下面內容:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = {//要設置的全局訪問的state對象
textData: "Data from index",
};
const store = new Vuex.Store({
state
});
export default store;
全局變量寫在state里。
2.修改變量
在需要修改的地方使用this.$store.state.textData =XXX進行修改:
watch: {
dbData: function() {
this.$store.state.textData = this.dbData;
}
}
3.獲取變量
在需要獲取的地方使用 XXX=this.$store.state.textData進行獲取:
data() {
return {
title: "11",
textData: ""
};
},
computed: {
text() {
return this.$store.state.textData; //需要監聽的數據
}
},
watch: {
text(newVal, oldVal) {
let that = this;
//do something
this.textData = newVal;
},
},