如何实现可接收key参数的Vuex动态getter以获取对应state数据
完全可以实现,Vuex getter本身支持返回函数来接收自定义参数,刚好适配这种批量同逻辑的取值场景。
改造后的代码实现
const getters = { // 动态getter:传入state对应的key即可返回对应值 getCountByKey: (state) => (key) => { // 可选边界校验:避免查询不存在的key时报错 if (!Object.hasOwn(state, key)) { console.warn(`state中不存在字段:${key}`) return } return state[key] } }
调用方式
- 直接在组件内调用:
this.$store.getters.getCountByKey('count')// 返回0this.$store.getters.getCountByKey('count2')// 返回1 - 配合
mapGetters辅助函数使用:import { mapGetters } from 'vuex' export default { computed: { ...mapGetters(['getCountByKey']) }, mounted() { console.log(this.getCountByKey('count3')) // 输出2 } }
注意事项
这种返回函数的动态getter不会缓存计算结果,每次调用都会重新执行。如果你有高频查询固定key的场景,可以单独保留对应静态getter,或者自行额外做缓存优化即可。
内容的提问来源于stack exchange,提问作者Nikola Pavicevic
相关产品推荐
相关产品推荐

