【发布时间】:2020-09-23 09:40:39
【问题描述】:
我有一个组件,我想在其中迭代具有计算属性的元素。
在正常情况下你会做这样的事情:
// Computed property
acquiredPrice: {
get () {
return value
},
set (value) {
// set the value with some vuex magic
},
},
然后像这样在模板中引用它:
<v-text-field
v-model="acquiredPrice"
>
</v-text-field>
这正如预期的那样工作。但是我想做以下事情
// computed property
steps () {
return [
{
allowed: true,
text: 'Some question?',
type: 'integer',
model: this.acquiredPrice, // reference to the computed property
},
]
},
<!-- inside template -->
<template v-for="step in steps">
<v-row
:key="step.text"
>
<v-col>
<h4>{{step.text}}</h4>
<!-- This does not work. Only in retrieving the value -->
<v-text-field
v-model="step.model"
>
</v-text-field>
</v-col>
</v-row>
</template>
所以核心问题是,当我遍历这些步骤并使用 step.model 来引用计算属性时,我会丢失 setter。即,当在字段中输入时,setter 方法永远不会被命中。
也许有一些方法可以通过字符串名称访问计算属性,所以我可以避免 dict 中的实际值?
例如(这只是我想要的伪代码)v-model=$computed['acquiredPrice']
可以在此处查看说明问题的完整 PoC:
<template>
<div class="">
<template v-for="step in steps">
<v-row
:key="step.text"
>
<v-col>
<h4>{{step.text}}</h4>
<!-- This does not work. Only in retrieving the value -->
<v-text-field
v-model="step.model"
>
</v-text-field>
</v-col>
</v-row>
</template>
<!-- This works just as expected -->
<v-text-field
v-model="acquiredPrice"
>
</v-text-field>
</div>
</template>
<script>
export default {
name: 'redacted',
props: {
},
data: () => ({
}),
computed: {
acquiredPrice: {
get () {
return value
},
set (value) {
// set the value with some vuex magic
// THIS IS NEVER HIT WHEN IT IS REFERENCED FROM step.model ON LINE 13
},
},
steps () {
return [
{
allowed: true,
text: 'Some question?',
type: 'integer',
model: this.acquiredPrice,
},
]
},
},
components: {
},
methods: {
},
mounted () {
},
}
</script>
【问题讨论】:
-
也许你可以使用观察者模式来代替
deep: true。 -
为什么不 v-bind 到
acquiredPrice?
标签: javascript vue.js vuejs2