利用vuex缓存常用数据,通过getter获取state中的数据和发送请求

思路
  1. 在getter中引入store, 并通过store.dispatch调用action中的方法请求数据设置到state中
代码逻辑分析

在页面使用computed属性,第一次调用getter时因为没有数据会调用action,同时返回state.list作为computed属性的依赖, 过了会儿action的异步方法调用完毕,state.list变化,依赖变化, 触发computed, 更新页面的list

下图可见getter调用了两次
在这里插入图片描述

代码

使用

import { mapGetters } from 'vuex'

  computed: {
    ...mapGetters([
      'professionList', // 从getter.js中获取下拉选择框的缓存, 可以减少请求
    ]),
  },

getter.js

import store from './index.js'

const getters = {
    professionList: (state) => {
        if (!state.cachedData.professionList) {
            store.dispatch('cachedData/getprofessionList')
        }
        console.log('state.cachedData', state.cachedData);
        return state.cachedData.professionList
    },
}
export default getters

cachedData.js

import http from '@/utils/request.js'
import { Message } from 'element-ui'

function awaitRequest(params, url) {
  return new Promise((resolve, reject) => {
    http({
      method: 'post',
      url,
      data: params,
    }).then(res => {
      if (res.code == 200) {
        resolve(res.data)
      } else {
        Message({type: 'error',message: res.status_desc})
        reject(res)
      }
    }).catch(() => {
      Message({type: 'error', message: '请求错误'})
    })
  })
}

const state = {
  professionList: null,
}

const mutations = {
  SET_PROFESSION_LIST: (state, data) => {
    state.professionList = data
  },
}

const actions = {
  async getprofessionList({ commit }) {
    const res = await awaitRequest({}, 'feakUrl')
    commit('SET_PROFESSION_LIST', res)
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值