當(dāng)前位置:首頁(yè) > IT技術(shù) > 移動(dòng)平臺(tái) > 正文

Vuex 存值與取值 (vue+vuex+axios從后臺(tái)獲取數(shù)據(jù)存入vuex,組件之間共享數(shù)據(jù))
2021-09-17 19:48:00

vue 各個(gè)組件之間傳值,基于父子、兄弟組件,傳值可能會(huì)很方便,但是如果是沒(méi)有關(guān)聯(lián)的組件之間要使用同一組數(shù)據(jù),vuex 就可以很好的解決。

組件從后臺(tái)獲取的數(shù)據(jù)存入vuex并使用:

?

1.如果沒(méi)有安裝vuex,要先安裝并在main.js中全局注冊(cè)

(1)安裝依賴包:npm install vuex --save

(2)全局使用:import?Store?from?'./store/index';

?

?

2.在store的index.js中:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    buttonPower:{}//初始化存的值
  },
  mutations: {
    setTest (state, data) {
      state.buttonPower = data;//data是state存的值
    }
  },
  actions: {
  },
  modules: {
  }
})

3.存值:組件內(nèi)從后臺(tái)獲取的數(shù)據(jù)

    getButtonList() {
      this.$http
        .get('sysMenu/queryButtonListByThird', {
          params: {
            thirdMenuId: this.thirdMenuId
          }
        })
        .then(res => {
          if (res.data.code === 0) {
            let buttonShow = res.data.data;
            buttonShow.map(item => {
              this.buttonPower[item] = true;
            });
            this.$store.commit('setTest', this.buttonPower);//存值:請(qǐng)求回來(lái)的數(shù)據(jù)
          }
        })
        .catch(err => {});
    }

4.取值:在需要使用數(shù)據(jù)的組件取值

   computed: {    
    getBtnPower() {
      return this.$store.state.buttonPower;
    }
  },
//在計(jì)算屬性中取值,之后賦在綁定值的地方就可以使用了

//例如:
?this.buttonPower?=?this.$store.state.buttonPower;
?<el-button?v-if="buttonPower.look"?type="text"? @click="handleView(scope.row)">查看</el-button>
?<el-button?v-if="buttonPower.edit"?type="text"? @click="handleEdit(scope.row)">編輯</el-button>
?

?

?

本次解決方法來(lái)自:https://blog.csdn.net/liming1016/article/details/110128522?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-2.no_search_link


深入理解Vuex的作用以及使用:參考 https://www.jb51.net/article/211938.htm

?

本文摘自 :https://www.cnblogs.com/

開(kāi)通會(huì)員,享受整站包年服務(wù)立即開(kāi)通 >