Vue.js:使用新数据处理数组并发布表单

时间:2017-05-19 14:11:17

标签: arrays forms post vue.js vuejs2

在我的Vue.js应用程序中,我想将表单数据发布到我的Node.js / MongoDB后端。

这是我的源代码:https://github.com/markusdanek/t2w-vue/blob/master/src/components/backend/JobEdit.vue

我的职位录入的JSON:http://t2w-api.herokuapp.com/jobs/591c09a55ba85d0400e5eb61

我的问题的相关代码:

HTML:

<div class="row">
    <input type='text' 
        :name="'qual'+index" 
        v-model="qualifications[index]">

    <button @click.prevent="removeQualifiaction(index)">X</button>
</div>

方法:

onChange(value, $event){
    if (!this.job.xmlOnline)
      this.job.xmlOnline = []

    const index = this.job.xmlOnline.findIndex(v => v == value)
    const checked = $event.target.checked

    if (checked && index < 0)
      this.job.xmlOnline.push(value)
    if (!checked && index >= 0)
      this.job.xmlOnline.splice(index, 1)
}

removeQualifiaction() {
    this.qualifications.splice(this.qualifications.index, 1);
}

使用表单结尾处的提交按钮发送表单数据:

editJob() {
    let job = Object.assign({}, this.job);
    job.qualifications = this.qualifications;
    job.responsibility = this.responsibility;
    this.$http.post('https://t2w-api.herokuapp.com/jobs/' + this.$route.params.id, job).then(response => {
      console.log(response);
    }, response => {
      console.log(response);
    });
}

我现在的问题:

当我编辑“工作”时,我有一个“资格项目”列表,它是我表单中的输入字段。

  

单击“删除”按钮会导致第一个输入被删除,而不是我点击的那个。 完成@thanksd回答。

     

如何添加按钮和方法以添加新输入字段并将其附加到我的job.qualifications?

在我的JobAdd.vue中实现,为job.qualifications添加一个新条目,如下所示:

<a @click.prevent="addQualification">+</a>

addQualification() {
    this.qualification.push({ text: '' });
}

addJob() {
    let job = Object.assign({}, this.job);
    job.qualifications = this.qualification.map(q => q.text);
    this.$http.post('https://t2w-api.herokuapp.com/jobs/', job).then(response => {....

我的JobAdd.vue的完整来源:https://github.com/markusdanek/t2w-vue/blob/master/src/components/backend/JobAdd.vue

当我的job.qualifications中已经有字符串时,

this.qualification.push({ text: '' });显然不在我的JobEdit.vue中。

1 个答案:

答案 0 :(得分:1)

更改removeQualifiaction方法以使用传入的索引:

removeQualifiaction(index) {
  this.qualifications.splice(index, 1);
}