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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM