我该如何解决“未捕获的TypeError:无法读取未定义的属性'get'",在Vuex商店中? [英] How can I solve "Uncaught TypeError: Cannot read property 'get' of undefined" in the vuex store?

查看:393
本文介绍了我该如何解决“未捕获的TypeError:无法读取未定义的属性'get'",在Vuex商店中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I try this .$session.get(SessionKeys.Cart) in my component like this :

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

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

It works. I success get session cart

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

But if I try it in the my vuex store like this :

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

如何解决此错误?

推荐答案

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

You can pass the component this into your dispatch function, called dispatching with a payload. like so:

<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
}

这篇关于我该如何解决“未捕获的TypeError:无法读取未定义的属性'get'",在Vuex商店中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆