Vuex 存值与取值 (vue+vuex+axios从后台获取数据存入vuex,组件之间共享数据)

时间:2021-09-24 02:22:00   收藏:0   阅读:33

vue 各个组件之间传值,基于父子、兄弟组件,传值可能会很方便,但是如果是没有关联的组件之间要使用同一组数据,vuex 就可以很好的解决。

组件从后台获取的数据存入vuex并使用:

 

1.如果没有安装vuex,要先安装并在main.js中全局注册

(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.存值:组件内从后台获取的数据

    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-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>
 

 

 

本次解决方法来自: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/angel648/p/15305926.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!