Как я могу решить "Uncaught TypeError: Невозможно прочитать свойство 'get' of undefined" в хранилище vuex? - PullRequest
0 голосов
/ 27 сентября 2018

Если я попытаюсь 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 голосов
/ 27 сентября 2018

Вы можете передать компонент 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
}
...