如何解决Vuex存储中的“未捕获的TypeError:无法读取未定义的属性'get'”?

时间:2018-09-27 04:12:40

标签: vue.js vuejs2 vue-component vuex vuex-modules

如果我在这样的组件中尝试this .$session.get(SessionKeys.Cart)

<template>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            add(item) {
                console.log(this.$session.get(SessionKeys.Cart)
                ...
            }
        }
    }
</script>

有效。我成功获得会话购物车

但是,如果我在这样的vuex商店中尝试使用它,

import { set } from 'vue'
// initial state
const state = {
    list: {}
}
// getters
const getters = {
    list: state => state.list
}
// actions
const actions = {
    addToCart ({ dispatch,commit,state },{data})
    {
        console.log(this.$session.get(SessionKeys.Cart))
        ...
    }
}
// mutations
const mutations = {
    ...
}
export default {
    state,
    getters,
    actions,
    mutations
}

存在错误:Uncaught TypeError: Cannot read property 'get' of undefined

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

您可以将组件this传递到分派函数中,这称为带有有效负载的分派。像这样:

<template>
    ...
</template>
<script>
    ...
    export default {
        ...
        methods: {
            this.$store.dispatch('addToCart', { data: {}, ctx: this })

            // add(item) {
            //    console.log(this.$session.get(SessionKeys.Cart)
            //    ...
            //}
        }
    }
</script>

import { set } from 'vue'

// initial state
const state = {
    list: {}
}

// getters
const getters = {
    list: state => state.list
}

// actions
const actions = {
    addToCart ({ dispatch, commit, state }, { data, ctx })
    {
        console.log(ctx.$session.get(SessionKeys.Cart))
        ...
    }
}

// mutations
const mutations = {
    ...
}

export default {
    state,
    getters,
    actions,
    mutations
}