Using vuexmodules
mutation-type
export const GET_TABGRADE = 'GET_TABGRADE'
api part code
const tanjie = axios.create({
baseURL: 'tanjie'
})
findGrade1: function () {
return new Promise((resovle, reject) => {
tanjie({
url: '/content/findGrade1'
}).then(response => {
console.log('api is transfer')
resovle(response.data)
}).catch(error => {
reject(error)
})
})
},
Module:
import baseApi from '@/api/base'
import * as types from '../mutation-type'
const state = {
tabGrade: {
errno: 1,
list: {}
}
}
const getters = {
getTabGrade: state => {
state.tabGrade
}
}
const actions = {
// 调用api
getTabGrade({ commit }) {
console.log('is actions')
return new Promise(function (resolve, reject) {
baseApi.findGrade1()
.then(res => {
commit(types.GET_TABGRADE, res)
resolve(res);
}).catch(err => {
console.log(err)
})
})
}
}
const mutations = {
[types.GET_TABGRADE](state, res) {
state.tabGrade = {
...state.tabGrade,
list: res.list
}
console.log(state.tabGrade)
}
}
export default {
state,
getters,
actions,
mutations
}
Inside component
computed: {
...mapGetters([
'getTabGrade'
]),
created() {
this.$store.dispatch('getTabGrade')
.then(res => {
console.log(res) // undefined
return res
})
.catch(err => {
console.log(err)
})
},
There should be no problem with the references to each module. After all, the component can be accessed through this.$store
state
But I don’t know why dispatch
returns undefined
The correct data can be obtained in the component. How can I use it, like displaying a grade1_name through {{}}
Added return and resolve, otherwise the call triggered by this.$store.dispatch('getTabGrade') may not return a promise with the correct value. Please try it.
Solved, I finally did some processing in the getter of the module:
The calculated properties are written in the final component using template syntax,
html:
js: