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

查看:113
本文介绍了我该如何解决“未捕获的类型错误:无法读取未定义的属性 '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
}

存在错误:未捕获的类型错误:无法读取未定义的属性get"

我该如何解决这个错误?

How can I solve this error?

推荐答案

您可以将组件 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
}

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

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