为什么在将参数传递给映射的 getter 时会得到 undefined? [英] Why do i get undefined when passing parameter to mapped getter?
问题描述
我设置了一些 getter,您向它们传递一个 id,它们返回相关数据.所以我已经将这些映射到一个组件中,但是当传递一个参数时,参数是未定义的.
组件:
<div><h1>{{ category.name }}</h1>
</模板><脚本>从 'vuex' 导入 { mapGetters }导出默认{道具:['id'],计算:mapGetters({subCategories: ['categories/getSubcategories'](this.id),类别:['categories/getCategory'](this.id)})}
吸气剂:
getCategory: (state, id) =>{返回 state.categories.filter(category => category.id === id);},
错误是:
<块引用>无法读取未定义的属性id"
如果我传递一个硬编码参数,例如 category: ['categories/getCategory'](106)
然后我得到:
['categories/getCategory'] 不是函数
我哪里出错了?
这是我的商店:
根据 这个 GitHub issue,看来你需要的是在你的getter中返回一个函数,然后在计算属性中调用该方法,即你的getter:
getCategory: state =>{返回 ID =>state.categories.filter(category => category.id === id);}
然后在 computed
属性中:
计算:{...mapGetters(['类别/获取子类别','类别/获取类别']),子类别 () {返回这个['categories/getSubcategories'](this.id)},类别 () {返回这个['categories/getCategory'](this.id)}}
I have some getters set up, you pass them an id and they return the relevent data. So i've mapped these into a component, however when passing a param the param is undefined.
Component:
<template>
<div>
<h1>{{ category.name }}</h1>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
props: ['id'],
computed: mapGetters({
subCategories: ['categories/getSubcategories'](this.id),
category: ['categories/getCategory'](this.id)
})
}
</script>
Getter:
getCategory: (state, id) => {
return state.categories.filter(category => category.id === id);
},
The error being:
Cannot read property 'id' of undefined
If I pass it a hard coded parameter, e.g category: ['categories/getCategory'](106)
then I get:
['categories/getCategory'] is not a function
Where am I going wrong here?
EDIT: Here's my store:
According to this GitHub issue, it seems what you need is to return a function in your getters and then call the method in the computed property, i.e. your getter:
getCategory: state => {
return id => state.categories.filter(category => category.id === id);
}
And then in computed
property:
computed: {
...mapGetters([
'categories/getSubcategories',
'categories/getCategory'
]),
subCategories () {
return this['categories/getSubcategories'](this.id)
},
category () {
return this['categories/getCategory'](this.id)
}
}
这篇关于为什么在将参数传递给映射的 getter 时会得到 undefined?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!