【问题标题】:Vue.js: Trying Array.push to have multiple inputs for one v-modelVue.js:尝试 Array.push 为一个 v-model 提供多个输入
【发布时间】:2017-10-10 19:54:11
【问题描述】:

我有一个带有“工作”模型的 MongoDB/Express 服务器。该作业包含一个字段“qualifications”,它是一个字符串数组。

我现在有一个 Vue.js 应用程序,它应该执行基本的 CRUD 功能。 所以我有一个 JobAdd.vue,里面有一个表格,里面有多个头衔、薪水等输入。 现在我的模型中有所谓的“资格”字段,所以在我的表单中,我希望资格字段有多个输入。但是像v-model="job.qualification[]"这样的v-model是不允许的。

这是我目前的申请:https://github.com/markusdanek/t2w-vue/blob/mdanek/2-auth-system/src/components/backend/JobAdd.vue

所以我尝试了以下方法:

<div v-for="qual in qualification">
    <input v-model="qual.text">
  </div>
  <button @click="addQualification">
    New Qualification
</button>

addQualification() {
    this.qualification.push({ text: '' });
    this.job.qualifications = this.qualification;
},

我的客户端现在有以下数据结构:

{
  "job": {
    "qualifications": [
      {
        "text": "You should do that"
      },
      {
        "text": "And have that"
      },
      {
        "text": "Lorem Ipsum"
      }
    ],
    "maxSalary": "1200",
    "title": "Test Title",
    "salary": "1234"
  },
}

我的方法的第一个问题:我需要这样的 job.qualification (http://t2w-api.herokuapp.com/jobs),而不是作为对象。

但我需要的是以下表示: http://t2w-api.herokuapp.com/jobs

这将呈现为:https://www.team2work.at/#/jobs/57d29740f9c4f703000eec2d

当我调用我的方法 addJob form (on.submit) 时,它什么也不做:

addJob: function() {
    this.job.qualifications = this.qualification;
    this.$http.post('http://localhost:9001/jobs/', this.job).then(response => {
      console.log(response);
    }, response => {
      console.log(response);
    });
  }
},

这里有什么解决方案吗?有人指出"You are binding v-model directly to a v-for iteration alias",但我认为它不能解决我的问题。

这是来自我现在正在转换为 Vue.js 的旧项目(Express/Handlebars):https://gist.github.com/markusdanek/dcfadf554a4a99549d3d232c52b84e2c

应该完全一样:-)

【问题讨论】:

标签: arrays mongodb object vue.js vuejs2


【解决方案1】:

如果您希望在提交时资格是一个字符串数组,只需映射您的资格,以您需要的格式返回它们。

let job = Object.assign({}, this.job)
job.qualifications = this.qualification.map(q => q.text)

this.$http.post("...", job)
...

您也可以删除此行,因为如果您采用这种方法,它似乎无关紧要。

addQualification() {
  this.qualification.push({ text: '' });
  //this.job.qualifications = this.qualification;
},

【讨论】:

猜你喜欢
  • 2018-05-12
  • 2018-01-09
  • 2016-04-21
  • 1970-01-01
  • 2019-11-08
  • 2015-11-02
  • 2018-07-12
  • 2018-07-04
  • 2020-07-18
相关资源
最近更新 更多