vue-cli2使用store存储全局变量

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;
    },
  },

猜你喜欢

转载自www.cnblogs.com/dxy9527/p/12938838.html