思路
- 在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
}