用的vuex的modules
mutation-type
export const GET_TABGRADE = 'GET_TABGRADE'
api部分程式碼
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)
})
})
},
模組:
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
}
元件內
computed: {
...mapGetters([
'getTabGrade'
]),
created() {
this.$store.dispatch('getTabGrade')
.then(res => {
console.log(res) // undefined
return res
})
.catch(err => {
console.log(err)
})
},
#各個模組的引用應該是沒有問題得,畢竟元件內可以透過 this.$store
來存取 state
但不知道為何 dispatch
會回傳 undefined
元件內可以得到正確的資料的,請問我該如何去使用,就像透過{{}}來展示一個grade1_name
加了return和resolve,不然this.$store.dispatch('getTabGrade')觸發呼叫可能沒有回傳有正確值的promise,你試試看。
已解決,我最後在模組的getter中做了處理:
最終元件中使用模板語法將計算屬性寫了上去,
html:
js: