Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vue.js - How can I solve "Uncaught TypeError: Cannot read property 'get' of undefined" in the vuex store?

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

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
}

There exist error : Uncaught TypeError: Cannot read property 'get' of undefined

How can I solve this error?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...