【发布时间】:2020-07-14 00:43:23
【问题描述】:
我有一个表单,当另一个字段被更新时,我需要更新多个其他表单字段。例如,我有一个联系人姓名,根据联系人姓名,我需要更新电子邮件和电话的值。
<template>
<custom-input :value="contact.name" @input="event => contact.name = event.target.value" />
<custom-input :value="contact.phone" @input="event => contact.phone = event.target.value" />
<custom-input :value="contact.email" @input="event => contact.email = event.target.value" />
</template>
<script>
...
props: {
contact: {
type: Object,
required: true
}
},
watch:
"contact.name": function(value) {
if (this.contact.name === "john") {
this.contact.email = "john@email.com"
this.contact.phone = "1111111111"
} else if (this.contact.name === "ed") {
this.contact.email = "ed@email.com"
this.contact.phone = "2222222222"
}
}
}
...
</script>
我知道 Vue 不喜欢这样,因为它将 DOM 与数据模型分开。我的第一个想法是使用$refs,但这些都是只读的。这样做的正确方法是什么?
我的另一个想法是将name 和phone 的值设置为计算属性。这样做的问题是它不会在父组件的表单上得到监视。
这也可能与我对“双向”绑定的误解有关。我一直认为表单是一种方式,而组件脚本中的数据是另一种方式,而事实并非如此。那么,还有什么办法呢?
我的最后一个想法是我可能不得不发出一个事件?
<template>
<custom-input :value="contact.name" @input="event => contact.name = event.target.value" />
<custom-input ref="phone" :value="contact.phone" @input="event => contact.phone = event.target.value" />
<custom-input ref="email" :value="contact.email" @input="event => contact.email = event.target.value" />
</template>
<script>
...
props: {
contact: {
type: Object,
required: true
}
},
watch:
"contact.name": function(value) {
if (this.contact.name === "john") {
this.$refs.email.$emit("input", "john@email.com")
this.$refs.phone.$emit("input", "111111111111")
} else if (this.contact.name === "ed") {
this.$refs.email.$emit("input", "ed@email.com")
this.$refs.phone.$emit("input", "222222222222")
}
}
}
这似乎也不起作用。真可惜。
编辑
修正语法错误
编辑 2
表明input实际上是一个单独的子组件
【问题讨论】:
-
除了
:value和@input的不必要分离(只使用v-model),我认为您在这里所做的没有任何问题。也许我误解了你的问题? -
@DecadeMoon 可悲的是它不起作用。应该吗?
-
没关系,我重新阅读了您的代码并发现了一些语法错误。看我的回答。
-
您所做的那些编辑清除了一切,谢谢。我仍然认为
v-model可以(并且应该)在这里使用,但是由于我们正在处理自定义组件,您可能不会收到它发出的input事件的本机事件对象。你能确认一下吗? -
@DecadeMoon 我怎么知道何时收到该事件?我知道它是基于 Vue 控制台触发的,但它会为
Error in v-on handler: "TypeError: Cannot read property 'value' of undefined"引发错误
标签: javascript vue.js frontend