简体   繁体   English

如何在Vue 2中的V模型中动态绑定值

[英]How to bind values dynamically in v-model in vue 2

I am facing an interesting problem. 我面临一个有趣的问题。 I have two tables of a user. 我有一个用户的两个表。 One table is users and another is information. 一个表是用户,另一个表是信息。 Now when signing up, userinfo table can be blank or filled. 现在注册时,userinfo表可以为空白或填充。 If filled then there is no problem. 如果已填充,则没有问题。

The problem, when I create a form to update/create(new record of userinfo as he didn't provide while signing up.) I try to get data from database and store in an object. 问题是,当我创建一个要更新/创建的表单(用户注册时未提供的新的userinfo记录)时,我尝试从数据库中获取数据并将其存储在对象中。 Something like this 像这样

    data(){
      return {
          data:user[0].userinfo
        }
    },

and in my form I auto populate the form using v-model 在我的表单中,我使用v模型自动填充表单

<input type="text" v-model="data.address" />

Clearly you see the problem. 显然您看到了问题。 Since this user has no records, the value of data will null 由于此用户没有记录,因此data的值将为null

On the other hand if the user provide the userinfo while signing up, these issue doesn't exists as there will be data. 另一方面,如果用户在注册时提供了userinfo,则不会存在这些问题,因为将会有数据。

How can I solve this errors? 我该如何解决这个错误?

Currently what I do is create conditional forms mean two forms. 目前,我要做的是创建条件形式,表示两种形式。 One for editing for the user whose data is available and one for editing. 一种用于为数据可用的用户编辑,另一种用于编辑。 But I have to create two forms and some extra coding. 但是我必须创建两种形式和一些额外的编码。 Is there any ways we escape errors and work with one form? 有什么方法可以避免错误并使用一种表格? Thank you/ 谢谢/

You could define your data property first as an empty object with all of the properties required by the form and then assign that object the userinfo : 您可以先将data属性定义为一个空对象,其中包含表单所需的所有属性,然后将该对象分配给userinfo

data() {
  let userData = {
    address: '',
    name: '',
    email: '',
  }

  return {
    data: Object.assign(userData, user[0].userinfo);
  }
},

This way, if there is no data in user[0].userinfo your data property will still have all of its needed properties defined. 这样,如果user[0].userinfo没有数据, user[0].userinfo您的data属性仍将定义其所有需要的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM