带参数的 vuexjs getter [英] vuexjs getter with argument
问题描述
有没有办法将参数传递给vuex
store
的getter?类似的东西:
new Vuex.Store({吸气剂:{一些方法(参数){//使用对 args 的查询从 store 返回数据}}})
这样我就可以在组件中使用
<div><p>{{someMethod(this.id)}}</p>
模板><script lang="ts">从vuex"导入 { mapGetters }导出默认{道具:['id'],计算:mapGetters(['someMethod'])}}
但在 vuex 中,第一个参数是 state
,第二个参数是其他 getter
.可能吗?
一种方法可以是:
new Vuex.Store({吸气剂:{一些方法(状态){var self = this;返回函数(参数){//从 store 返回数据,查询 args 和 self as this};}}})
但是,getter 不接受参数,并且在此线程中解释了原因:
<块引用>命名约定有点混乱,getter 表示状态可以以任何形式检索,但实际上它们是reducer.
也许我们应该让 reducer 成为纯方法.可用于过滤、映射等.
getter 可以被赋予任何上下文.与计算类似,但您现在可以在 vuex 选项中将计算道具与 getter 结合起来.这有助于组件的结构.
实现相同目的的更好方法是使用 nivram80 的答案中详述的 ES6 箭头,使用method style getters 在这里你可以通过返回一个函数来传递参数形成吸气剂:
new Vuex.Store({吸气剂:{someMethod: (state) =>(id) =>{返回 state.things.find(thing => thing.id === id)}};}})
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>
but in vuex first argument is state
and second is other getters
. Is it possible?
One way to do this can be:
new Vuex.Store({
getters: {
someMethod(state){
var self = this;
return function (args) {
// return data from store with query on args and self as this
};
}
}
})
However, getter does not take arguments and why is explained in this thread:
the naming convention is slightly confusing, getters indicates state can be retrieved in any form, but in fact they are reducers.
Perhaps we should have reducers being pure methods. Which can be used for filtering, mapping ect.
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.
Edit:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!