1

如果我尝试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

我该如何解决这个错误?

4

1 回答 1

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
}
于 2018-09-27T15:33:20.900 回答