javascript - Regarding vuex, what is known is that the dispatch method is called in the component, and the return value is undefined. I don't know what went wrong.
我想大声告诉你
我想大声告诉你 2017-07-05 10:41:22
0
2
1642

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 throughthis.$storestate

But I don’t know whydispatchreturnsundefined

The correct data can be obtained in the component. How can I use it, like displaying a grade1_name through {{}}

我想大声告诉你
我想大声告诉你

reply all (2)
给我你的怀抱

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.

const actions = { // 调用api getTabGrade({ commit }) { console.log('actions') return baseApi.findGrade1() //添加return .then(res => { commit(types.GET_TABGRADE, res) resolve(res); //添加resolve }).catch(err => { console.log(err) }) } }
    刘奇

    Solved, I finally did some processing in the getter of the module:

    const getters = { getTabGrade: state => { console.log('getter',state.tabGrade) let tabGradeName = [] for(var i =0; i

    The calculated properties are written in the final component using template syntax,
    html:

    {{getTabGrade[0]}}

    js:

    computed: { ...mapGetters([ 'getTabGrade' ])
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!