【问题标题】:Vue.js: Manipulate Array and post form with new dataVue.js:使用新数据操作数组并发布表单
【发布时间】:2017-10-19 17:10:00
【问题描述】:

在我的 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 中显然不起作用。

【问题讨论】:

    标签: arrays forms post vue.js vuejs2


    【解决方案1】:

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

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

    【讨论】:

    • 这么简单!知道如何添加新输入吗?
    • @mrks 这是一个模糊的问题(可能需要另一个帖子)。向视图动态添加输入?
    • 编辑了我的问题,也添加了更多信息,说明我是如何在 JobAdd.vue 中做到这一点的——现在的问题是,当我想编辑一个作业时,我的数组 job.qualifications 中已经存储了字符串。 @thanksd
    • @mrks 是的,这确实应该是一个单独的问题帖子。每个问题都应该有一个 Minimal, Complete, and Verifiable 单个问题的示例,以便它对人们将来找到您的问题最有用。
    猜你喜欢
    • 1970-01-01
    • 2023-03-10
    • 2012-05-06
    • 2020-12-21
    • 2016-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    相关资源
    最近更新 更多