javascript – 将参数传递给Vuex中的getter
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 将参数传递给Vuex中的getter,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1833字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 将参数传递给Vuex中的getter](/upload/InfoBanner/zyjiaocheng/812/3f68bfb656164e70a0260b0d64e11193.jpg)
我有一个像这样的Vue组件:
<script>
import { mapActions, mapGetters } from 'vuex'
export default {
props: ['index'],
computed: {
...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
])
}
</script>
<template>
<div :class='["block","module-"+type(index), "width"+width(index), "height"+height(index)]'>
<h3>{{ description(index) }}</h3>
<div class="data">
<h1>{{ tagValue(index) }}</h1>
<h2 class="measure">{{ smtTagMeasureUnits(index) }}</h2>
</div>
</div>
</template>
<style>
...
</style>
参数索引作为prop进入组件,已成功传递给getter:
getters: {
...
type: (state, getters) => (par) => {
return getters.widgetsConfig[par].type
},
width: (state, getters) => (par) => {
if (getters.widgetsConfig[par].width) {
return getters.widgetsConfig[par].width
} return 2
},
height: (state, getters) => (par) => {
if (getters.widgetsConfig[par].height) {
return getters.widgetsConfig[par].height
} return 1
},
...
}
工作正常,但我对这种代码风格不满意,因为getterName(index)在模板部分不断重复.我的所有getter都应该将索引作为prop,所以我想在模板中只使用getterName,脚本部分就是这样的:
...mapGetters([
'type',
'width',
'height',
'description',
'smtTagMeasureUnits',
'tagValue'
], index)
是否有可能在这里实现任何代码改进?
解决方法:
您始终可以创建返回getter结果的计算属性.就像是:
export default {
props: ['index'],
computed: {
...mapGetters([
'getTypeFromIndex',
'getWidthFromIndex',
'getHeightFromIndex'
]),
height(): { return this.getHeightFromIndex(index) },
width(): { return this.getWidthFromIndex(index) },
type(): { return this.getTypeFromIndex(index) },
//going a step further to clean up your templates...
classList: [
"block",
"height"+this.height,
"width"+this.width,
]
}
这样你只需要模板中的高度而不是高度(索引),甚至只需要classList,如果你把它拿走那么远
这里也引用了这个:https://github.com/vuejs/vuex/issues/688,我找不到它,但我知道我已经看过Evan You推荐的github问题了.
内容总结
以上是互联网集市为您收集整理的javascript – 将参数传递给Vuex中的getter全部内容,希望文章能够帮你解决javascript – 将参数传递给Vuex中的getter所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。