映射的吸气剂未定义

时间:2018-10-23 09:06:34

标签: vue.js vuejs2 vuex

我已经将一组吸气剂映射到我的组件中,并试图在方法中使用参数来调用它们,但是这些吸气剂却以未定义的形式出现。我在previous question

上回答后将它们映射了
computed: {
    ...mapGetters([
        'products/getCategoryProducts', 
        'categories/getSubcategories', 
        'categories/getCategory'
    ]),

    products () {
        return this['products/getCategoryProducts'](this.id)
    },

    subCategories () {
        return this['categories/getSubcategories'](this.id)
    },

    category () {
        return this['categories/getCategory'](this.id)
    },
}

错误为:

  

TypeError:this.categories / getCategory不是函数

我已经在控制台上登录了this

console.log(this)

console.log(this) continued

编辑:@Luceos回答后的更新代码:

computed: {
    ...mapGetters({
        getProducts: 'products/getCategoryProducts', 
        getSubCategories: 'categories/getSubcategories', 
        getCategory: 'categories/getCategory'
    }),

    products () {
        return this.getProducts(this.id)
    },

    subCategories () {
        return this.getSubCategories(this.id)
    },

    category () {
        return this.getCategory(this.id)
    },
}

哪个返回:

  

TypeError:this.getCategory不是函数

我的吸气剂:

getCategory: (state, id) => {
    return state.categories.filter(category => category.id === id);
}

2 个答案:

答案 0 :(得分:3)

尝试一下:

computed: {
    ...mapGetters({
        products: 'products/getCategoryProducts', 
        subcategories: 'categories/getSubcategories', 
        category: 'categories/getCategory'
    }),

    products () {
        return this.products(this.id)
    },

    subCategories () {
        return this.subcategories(this.id)
    },

    category () {
        return this.category(this.id)
    },
}

例如,您的getter应该是带有id的函数

getCategory: (state) => (id) => {
    return state.categories.filter(category => category.id === id);
}

请务必查看文档Method-Style Access

答案 1 :(得分:1)

根据documentation,您可以将其重构为使用对象样式访问器:

...mapGetters({
  // map `this.doneCount` to `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

所以在您的情况下:

computed: {
    ...mapGetters('products', {
        products: 'getCategoryProducts'
    }),
    ...mapGetters('categories', {
        subCategories: 'getSubcategories', 
        category: 'getCategory'
    }),
}

然后使用它(假设那些吸气剂有参数):

this.products(this.id)

我看过shopping cart example,这是他们的摘录,对上面的内容进行了更新以匹配:

...mapGetters('cart', {
      products: 'cartProducts',
      total: 'cartTotalPrice'
    })