如果我在这样的组件中尝试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
如何解决此错误?
答案 0 :(得分: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
}