Vuex 存值與取值 (vue+vuex+axios從後臺獲取資料存入vuex,元件之間共享資料)
阿新 • • 發佈:2021-09-17
vue 各個元件之間傳值,基於父子、兄弟元件,傳值可能會很方便,但是如果是沒有關聯的元件之間要使用同一組資料,vuex 就可以很好的解決。
元件從後臺獲取的資料存入vuex並使用:
1.如果沒有安裝vuex,要先安裝並在main.js中全域性註冊
(1)安裝依賴包:npm install vuex -
-save
(2)全域性使用:importStorefrom'./store/index';
2.在store的index.js中:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default newVuex.Store({ state: { buttonPower:{}//初始化存的值 }, mutations: { setTest (state, data) { state.buttonPower = data;//data是state存的值 } }, actions: { }, modules: { } })
3.存值:元件內從後臺獲取的資料
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);//存值:請求回來的資料 } }) .catch(err => {}); }
4.取值:在需要使用資料的元件取值
computed: { getBtnPower() { return this.$store.state.buttonPower; } },this.buttonPower=this.$store.state.buttonPower; <el-buttonv-if="buttonPower.look"type="text" @click="handleView(scope.row)">檢視</el-button> <el-buttonv-if="buttonPower.edit"type="text" @click="handleEdit(scope.row)">編輯</el-button>
//在計算屬性中取值,之後賦在繫結值的地方就可以使用了
//例如:
本次解決方法來自: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