使用状态管理vuex存取数据。

本篇博客先介绍使用方法,再介绍集成环境。

使用:

 

图①

如图①,Auxiliary页面想要获取index页面的数据。

在store目录的modules目录下新建layout.js文件。

layout.js代码如下:

// 状态管理: 存储用户在 布局页面中 选择的 树结构数据;


// state可以类比vue实例中的data(){return{}}
const state = {
    treeData: [],
    
    // (补充 10月11)
    data: [],
}


// mutations可以类比vue实例中的methods:{}
const mutations = { // 修改setters里面的内容
    // 同步
    set_tree_data(state, treeData) { // 提供
        // console.warn('state treeData', treeData)
        state.treeData = treeData
    },
    clear_tree_data(state) { // 清理
        state.treeData = []
    },

    // (补充 10月11)
    SET_DATA(state, data) {
      state.data = data;
    },
}

// 与mutations类似;
const actions = {
    // 异步, 从服务器请求回来的数据
    fetchTreeData({commit}, payload) {
        // 假设这是从服务器获取数据的异步操作
        // 这里使用 Promise 作为示例
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                const data = payload; // 假设数据已经从服务器获取到了
                // 提交mutation来更改状态
                commit('set_tree_data', data);
                resolve(['1','2']);
            }, 1000);
        })
    },

    // (补充 10月11)
    fetchData({ commit }, params) {
      // 异步请求数据
      api.yourDefinedGetData(params).then(response => {
        // 提交mutation来更改状态
        commit('SET_DATA', response.data);
      });
    },

}

// 类比vue实例中的computed:{}
const getters = {
    // 定义一个 getter 来过滤 id 等于 1 的树形数据返回
    filterTreeData(state) {
      return state.treeData.filter(item => item.id === 1);
    }
}


export default {
    namespaced: true, //为当前模块开启命名空间 (命名空间 layout)
    state,
    mutations,
    actions,
    getters
}

index页面存储数据到状态管理:


import { mapMutations } from 'vuex'
methods: {

    // 使用辅助函数获取 mutation
    ...mapMutations('layout',['set_tree_data','clear_tree_data']),
    // mapMutations 用于将 store 中的 mutations 方法映射为组件的方法。
    // 不只是 mapMutations 这一个辅助函数,MapActions、mapState、mapGetters
    // 辅助函数将 store 中的方法映射为组件方法;    


    setVuexData() {
      // 调用 set_tree_data方法 存储数据到layout.js文件
      this.set_tree_data(this.staticTreeData); 
    },

    // (补充 10月11)
    // 获取 mutation 的另一种方式,
    // 在methods中直接调用this.$store.commit, 而不是映射到局部方法;
    changeVuexStateData(){
        // 提交 mutation 改变(设置、存储)定义在state中treeData的值; 
        // 意义同上面的setVuexData;
        this.$store.commit('set_tree_data', this.staticTreeData) // 不推荐;
    },
},
data(){
    return{
        staticTreeData:
          [{
            id: 1,
            label: '一级 1',
            children: [{
              id: 4,
              label: '二级 1-1',
            }]
          },
          {
            id: 2,
            label: '一级 2',
            children: [{
                id: 5,
                label: '二级 2-1'
            }, {
                id: 6,
                label: '二级 2-2'
            }]
        }],
    }
},
mounted:{
    this.setVuexData()
}
Auxiliary页面从状态管理获取数据:

import { mapState } from 'vuex'

  computed: {
    // 使用辅助函数获取 state
    ...mapState('layout',{
      treeData: state => state.treeData
    }),
    // this.treeData 获取到state


    // (补充 10月11)
    // (获取state的另一个方式) 直接在计算属性中访问:
    stateTreeData(){
        return this.$store.state.treeData  // 不推荐这样,建议使用辅助函数映射到局部方法;
    },

    // 使用辅助函数获取 getters
    ...mapGetters('layout',['filterTreeData']),

    // (获取getters的另一个方式): (补充 10月11)
    getterFilterTreeData() {
        return this.$store.getters.filterTreeData;
    },
    
  },

  methods: {

    // 使用辅助函数获取 actions
    ...mapActions('layout',['fetchTreeData']),
    
    // 获取存储在状态管理的treeData;
    getVuexStateData(){
        let stateData = this.treeData;
        console.log('stateData: ', stateData);
    },
    getVuexGettersData(){
        let gettersData = this.filterTreeData
        // this.getterFilterTreeData 效果一样
        console.log('gettersData: ', gettersData);
    },
    getVuexActionsData(){
        let actionsData = this.fetchTreeData
        console.log('actionsData: ', actionsData);
    },

    // (补充 10月11)
    clickBtn(){ // 假设是一个按钮的点击事件来加载数据;
        // 不使用辅助函数 触发Vuex action的另一个方法:
        this.$store.dispatch('fetchData', { id: 1 }) // actions名称,参数;
        // this.$store.dispatch('fetchData', { id: 1 }) 
        // 这一行代码的作用是触发名为fetchData的action,并且传递参数params给这个action。
        // action内部可以执行异步操作,如API请求,并通过commit提交mutation来更新状态。
    },
    
  },

  mounted: {
    this.getVuexStateData()
    this.getVuexGettersData()
    this.getVuexActionsData()
  }  

如此,便介绍完使用方法。

补充getters:

在 Vuex 中,getters 类似于 Vue.js 组件中的计算属性(computed properties),但它们是在 Vuex store 的级别上定义的。getters 允许你基于 store 的状态派生出一些新的状态,这些状态通常是 store 中状态的复杂组合或经过某些处理后的结果。

getters是为了方便使用,与计算属性computed类似。随着modules下面的组件的值变化。

补充actions:( 10月11补充)

this.$store.dispatch是用于触发一个action的方法。在Vuex中,actions是处理异步操作的地方,它们可以触发mutations来改变state。

下面介绍集成环境:

环境集成vuex:

整体目录如图①所示。

如下图②在store目录下新建index.js文件:

图②

其中特别的,如本例中的layout组件位于modules目录下,不用再行注册。

如本例中的getters不在modules目录下,是需要注册的。

store目录下的index.js文件如下:

import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
Vue.use(Vuex)


const modulesFiles = require.context('./modules', true, /\.js$/)
// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})


const store = new Vuex.Store({
  modules, // 包含了modules目录下的所有文件;
  getters

})

export default store

main.js是程序的入口,需要在里面注册:

import Vue from 'vue'
import store from './store'

new Vue({
  el: '#app',
  store,
  render: h => h(App)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值