问题描述
有没有办法将参数传递到 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:
也许我们应该让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箭头,详见的答案,使用,您可以通过返回函数传递参数形成吸气剂:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!