javascript - 具有 20 多个属性的双向计算属性 (get,set)
问题描述
我有一个包含 20 多个属性的组件,我想将这些属性转换为如下所示的双向计算机属性。问题是这些属性的唯一列表很长(实际上是 28 个),因此转换所有属性将非常重复,并且会占用大量不必要的空间。有什么我不知道的技巧可以让它看起来干净吗?
computed: {
exp: {
get () {
return this.job.exp
},
set (value) {
this.$emit('job', { exp: value })
}
},
fund: {
get () {
return this.job.fund
},
set (value) {
return this.$emit('job', { fund: value})
}
},
// more to come
}
this.$emit('job', arg)
发出时使用的以下方法:
updateJob (object, source) {
for(const [key, value] of Object.entries(object)){
this.job[key]
? this.job[key] = value
: this.$set(this.job, key, value)
}
},
解决方案
您可以将$watch
api与deep: true
选项一起使用。这是一个带有增量函数的基本实现:
new Vue({
el: "#app",
data: {
job: {
a: 11,
b: 22,
c: 33,
d: 44,
e: 55,
f: 66,
g: 77,
h: 88,
// ...
},
},
created() {
// use $watch interface with the deep option
this.$watch('job', (newVal, oldVal) => {
// check for changes from the previous state
Object.keys(newVal).forEach(key => {
if(newVal[key] !== oldVal[key]) {
console.log('changed job attr', key, newVal[key])
this.$emit('job', {[key]: newVal[key]})
}
})
}, {deep: true})
},
methods: {
increment(key) {
// needs to be reassigned rather than mutated if you want
// the $watch callback to get the correct oldVal
const val = this.job[key] + 1
this.job = Object.assign({}, this.job, {[key]: val})
}
},
})
html来演示增量函数:
<div id="app">
<ul>
<li v-for="(val, key) in job" :key="key" @click="increment(key)">
{{ key }}: {{ val }}
</li>
</ul>
</div>
推荐阅读
- c# - 将数据表导出到多语言内容的 Excel
- c++ - LibHaru 库出现问题
- snowflake-cloud-data-platform - Snowflake 过程中 While 循环中的 IF 条件
- microsoft-forms - 我如何知道是否有人回答了排序顺序 MS Forms 问题或只是保留了默认顺序?
- javascript - 滚动到部分时更改 URL
- android - ImageView 适合有限空间并保持相同的缩小比例
- arrays - 比较 A 和 B 列表并创建一个 C 列表,其中 B 值不在 Powershell 的 A 列表中
- python - 关于如何在 Python 中创建 CrossTab 的困惑
- c# - StarSchema - 实体框架核心 - 迁移
- r - 计算人口年龄四分位数范围并将结果存储为 R 中的数据框的最佳方法