javascript - vue Js从对象绑定(bind)到数组

标签 javascript node.js vue.js vuejs2

我在 vue js 中有这个组件,它有一个绑定(bind)输入值的属性,我有一个方法将对象推送到数组,并且我将数组绑定(bind)到表,以便每次用户单击“添加”时按钮,它获取输入值并将其添加到表中。当我按添加时,它可以工作,但它也绑定(bind)从输入输入的值,我需要它仅推送该值并随后清除输入,以便可以创建新的详细信息。

<template>
<div>
    <div id="patientDetails">
    <div class="patient-add">
        <div>
            <label>Patient Name: </label>
            <input type="text" v-model="patientActive.name"/>
        </div>
        <div>
            <label>Patient Disease: </label>
            <input type="text" v-model="patientActive.disease"/>
        </div>
        <div>
            <button v-on:click="addPatientDetails()">Add +</button>
        </div>
    </div>
    <table>
        <thead>
            <th>Name</th>
            <th>Mobile</th>
        </thead>
        <tbody>
            <tr v-for="p in patients">
                <td>{{ p.name }}</td>
                <td>{{ p.disease }}</td>
            </tr>
        </tbody>
    </table>
</div>
</div>

这是 Vue 脚本:

export default {
name: 'patient',
data(){
    return {
        patientActive:{
          name: '',
          disease: ''
        },
        patients: []
    }
},
methods: {
    addPatientDetails(){
        var thispatient = this.patientActive;
        if(this.validatePatient()){
            this.patients.push(thispatient)
            console.log(this.patients)
        }
        //this.clearPatient()
    },
    validatePatient: function(){
        if(!this.patientActive.name){
            alert('Name is Invalid or Empty')
            return false
        }
        if(!this.patientActive.disease){
             alert('Disease is Invalid or Empty')
              return false
        }
        return true
    },
    clearPatient: function (){
        this.patientActive.name = ''
        this.patientActive.disease = ''
    }
}

最佳答案

在 javascript 中对象是 passed by reference 。数组也是对象,因此同样适用。

在您的 addPatientDetails 方法中,不要传递对 this.PatientActive 对象的引用,而是在任何推送到 患者 时创建该对象的副本数组。

addPatientDetails() {
  if (this.validatePatient()) {
    this.patients.push({ ...this.patientActive });
    console.log(this.patients);
  }
  this.clearPatient();
},

这是working fiddle

关于javascript - vue Js从对象绑定(bind)到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51244807/

相关文章:

node.js - 无法读取未定义的属性 “send”

javascript - 在 Node.js 中导出 Mongoose 代码 - 将值从 Mongoose 方法传递给回调

vue.js - VuetifyLoaderPlugin 错误找不到 vue-loader 的匹配规则

loops - 我怎样才能 "while loop"一个 Axios GET 调用直到满足条件?

javascript - Jquery 使用名称属性

javascript - 如何使用 JavaScript 在字符串中查找数字?

javascript - AngularJS 网页,持续加载

javascript - 为什么要用一个复杂的函数来计算字符串的长度而不是 string.length?

node.js - 构建运行时出现 webpack 错误。 'Error: Cannot find module ' @webassemblejs/ast''

javascript - Uncaught ReferenceError : Seed is not defined