vuexjs getter with argument [英] vuexjs getter with argument

查看:116
本文介绍了vuexjs getter with argument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将参数传递到 vuex 商店的getter?
类似于:

Is there a way to pass parameter into getter of vuex store? Something like:

new Vuex.Store({
  getters: {
    someMethod(arg){
       // return data from store with query on args
    }
  }
})

因此在组件中我可以使用

So that in component I could use

<template>
    <div>
        <p>{{someMethod(this.id)}}</p>
    </div>
</template>
<script lang="ts">
    import { mapGetters } from "vuex"

    export default {
        props: ['id'],
        computed: mapGetters(['someMethod'])
        }
    }
</script>

但是在vuex第一个参数是和第二个是其他 getters 。有可能吗?

but in vuex first argument is state and second is other getters. Is it possible?

推荐答案

一种方法可以是:

new Vuex.Store({
  getters: {
    someMethod(state){
      var self = this;
       return function (args) {
          // return data from store with query on args and self as this
       };       
    }
  }
})

但是,getter不接受参数,为什么在主题

However, getter does not take arguments and why is explained in this thread:


命名约定略有混淆,getters表示状态可以可以以任何形式检索,但事实上它们都是减速器。

the naming convention is slightly confusing, getters indicates state can be retrieved in any form, but in fact they are reducers.

也许我们应该让Reducer成为纯粹的方法。哪个可用于过滤,映射等。

Perhaps we should have reducers being pure methods. Which can be used for filtering, mapping ect.

getters然后可以给出任何上下文。与计算类似,但您现在可以将计算出的道具与vuex选项中的getter相结合。这有助于组件的结构。

getters then can be given any context. Similar to computed, but you can now combine computed props to getters in vuex option. Which helps structure of components.

编辑:

实现相同目标的更好方法是使用ES6箭头,详见 nivram80 的答案,使用方法样式获取者,您可以通过返回函数传递参数形成吸气剂:

A better way to achieve the same thing will be using ES6 arrow as detailed out in the answer of nivram80, using method style getters where you can pass a parameter by returning a function form the getter:

new Vuex.Store({
  getters: {
    someMethod: (state) => (id) => {
        return state.things.find(thing => thing.id === id)
      }
    };       
  }
})

这篇关于vuexjs getter with argument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆