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