猿问

在 vue 中以编程方式更新多个输入

我有一个表单,当另一个字段被更新时,我需要更新多个其他表单字段。例如,我有一个联系人姓名,根据联系人姓名,我需要更新电子邮件和电话的值。


<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计算属性的值。这样做的问题是它不会在父组件的表单上得到监视。


这也可能与我对“双向”绑定的误解有关。我一直认为表单是一种方式,而组件脚本中的数据是另一种方式,而事实并非如此。那么,另一种方法是什么?


我的最后一个想法是我可能不得不发出一个事件?


互换的青春
浏览 109回答 1
1回答

月关宝盒

我刚刚注意到您正在尝试修改propsVue 禁止的值。所有子组件都不能修改props从父组件传来的数据,因为它使数据流更难理解。您可以在官方网站上阅读更多相关信息:https ://vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow这就是为什么 Vue 也有data可以被组件修改的本地私有内存。因此,要解决您的问题,您需要在挂载子组件时将数据复制props到子组件上,并改为修改 的值。datadata这是更新的代码示例(Codepen 也更新了),它完全符合您的要求。模板:<div id="app">&nbsp; <div>&nbsp; &nbsp; <my-form :contact="contact"></my-form>&nbsp; </div></div>Javascript:Vue.component('my-form', {&nbsp; data() {&nbsp; &nbsp; return { name: '', phone: '', email: '' }&nbsp; },&nbsp; props: {&nbsp; &nbsp; contact: { type: Object, required: true }&nbsp; },&nbsp; mounted() {&nbsp; &nbsp; this.name = this.contact.name;&nbsp; &nbsp; this.phone = this.contact.phone;&nbsp; &nbsp; this.email = this.contact.email;&nbsp; },&nbsp; template: `&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <input v-model="name" />&nbsp; &nbsp; &nbsp; <input v-model="phone"/>&nbsp; &nbsp; &nbsp; <input v-model="email"/>&nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; value of input: {{ JSON.stringify({ name, phone, email }) }}&nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; </div>&nbsp; `,&nbsp; &nbsp; watch: {&nbsp; &nbsp; &nbsp; name(value) {&nbsp; &nbsp; &nbsp; &nbsp; if(value === 'john') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.phone = '123456';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.email = 'test@gmail.com';&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }});new Vue({&nbsp; el: '#app',&nbsp; data() {&nbsp; &nbsp; return { contact: { name: 'initial name', phone: '123456', email: 'initial.email@gmail.com' } }&nbsp; }})还有我更新的代码笔:https ://codepen.io/aptarmy/pen/PoqgpNJ
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答