search

Home  >  Q&A  >  body text

javascript - vuex reports an error this.$store.dispatch is not a function, how to solve it?

After copying the official vuex example before, I planned to make a demo with complete HTML, CSS, and more complete functions. Then it was basically completed. When I started testing, I encountered a background error " this.$store.dispatch is not a function”
I didn’t get it right all afternoon. I compared the examples for a long time and still didn’t see the problem. I used vue’s official chrome The debugger knows that state and getters are introduced, so state and actions do not get the data I simulated

The relevant codes are as follows

//Product.vue
import { mapGetters, mapActions } from 'vuex'
export default {
...
created () {
        this.$store.dispatch('getAllDetails')
    }
}
//store/modules/product.js
import shop from '../../api/shop'
import * as types from '../mutation-types'
const state = { all:[] }
const actions = {
    getAllDetails({ commit }) {
        shop.getDetails( details => {
            commit(types.PRODUCT_DETAILS, { details })
        })
    }
}

const mutations = {
    [types.PRODUCT_DETAILS] (state, { details }) {
        state.all = details
    }
}

export default {
    state,
    getters,
    actions,
    mutations
}
//store/mutations-types
export const PRODUCT_DETAILS = 'PRODUCT_DETAILS'
//shop.js
const _details = [{
    iPhone6S: {
      name: 'Apple/苹果 iPhone 6S',
      desc: '3D Touch、1200万像素照片、4k视频,强大功能于一身。',
      price: '5288 - 6888',
      style: {
        '银色': 'http://o8yu724qs.bkt.clouddn.com/iphone6s-silver-select-2015.png',
        '深空灰色': 'http://o8yu724qs.bkt.clouddn.com/iphone6s-gray-select-2015.png',
        '金色': 'http://o8yu724qs.bkt.clouddn.com/iphone6s-gold-select-2015.png',
        '玫瑰金色': 'http://o8yu724qs.bkt.clouddn.com/iphone6s-rosegold-select-2015.png'
      },
      activeStyleUrl: 'http://o8yu724qs.bkt.clouddn.com/iphone6s-silver-select-2015.png',
      size: {
        '16GB': 5288,
        '64GB': 6088,
        '128GB': 6888
      }
    }
}]
export default {
    getDetails (cb) {
        console.log(cb)
        return cb(_details)
    }
}

If you have time, or feel that the clips I captured cannot explain the problem, you can download the full version from github for debugging. Thank you in advance.

仅有的幸福仅有的幸福2709 days ago3087

reply all(2)I'll reply

  • 阿神

    阿神2017-07-05 10:43:57

    Modify main.js

    import * as store from './store'

    import store from './store'

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 10:43:57

    //Product.vue
    import { mapGetters, mapActions } from 'vuex'
    export default {
    ...
    created () {
            this.$store.dispatch('getAllDetails')
        }
    }

    You must first introduce store into your code, import store from './store'

    reply
    0
  • Cancelreply