Reputation: 13162
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?
Upvotes: 2
Views: 911
Reputation: 56
you can do this
import Vue from 'vue’
const session = Vue.prototype.$session;
at the top of your store and in your action method
console.log(session.get(SessionKeys.Cart))
this will work
Upvotes: 0
Reputation: 2753
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
}
Upvotes: 1