0

我正在使用一个名为Vue-Multiselect的“类型和搜索”插件,让用户能够在数据库中搜索客户名称。如果名称存在于数据库/下拉列表中,他们可以选择该名称,它将自动填充字段。

但是,如果名称不存在,我如何让用户能够在字段中输入新名称?场景:用户想要添加一个数据库中不存在的新名称注意:我确实有一个 ApiService,我将在提交表单时将其发布到。

这是我的模板代码(也可在JSFIDDLE中找到):

<multiselect 
    v-model="customer_last_name" 
    :options="options"
    placeholder="Select an existing customer or type to add a new one"
    :custom-label="customerSelectName"
    label="lastname"
    track-by="uid"
    :close-on-select="true" 
    :clear-on-select="false" 
    :hide-selected="true" 
    :preserve-search="true"  
    id="example"
    @select="onSelect"
  >
  </multiselect>

<!--           <label for="customer_first_name_input">First Name:</label><br>
          <input id="customer_first_name_input" type="text" v-model="customer_first_name" /> -->

脚本:

new Vue({
    components: {
    Multiselect: window.VueMultiselect.default
    },
    data: {
    customer_last_name: '',
    customer_first_name: '',
    options: [{"uid":"1","firstname":"John","lastname":"Doe","email":"johndoe@aol.com","phone":null,"c_organization":"ACME","c_title":null}, {"uid":"2","firstname":"Mary","lastname":"Smith","email":"msmith@aol.com","phone":null,"c_organization":"NBA","c_title":"Miss"}]
    },
  methods: {
    customerSelectName (option) {
      return `${option.lastname}, ${option.firstname}`
    },
    onSelect (option, uid) {
        console.log(option, uid)
    }
  }
}).$mount('#app')
4

1 回答 1

0

vue-multiselect库允许此tags功能。

你需要添加:taggable="true" @tag="addTag" :multiple="false"

并添加一个 addTag 方法:

addTag (newTag) {
  const parts = newTag.split(', ');

  const tag = {
    uid: this.options.length + 1,
    firstname: parts.pop(),
    lastname: parts.pop()
  };
  this.options.push(tag);
  this.customer_last_name = tag;
}

这只是一个示例方法,可以将输入转换Chavez, Martha为:

{
  "uid": 3,
  "firstname": "Martha",
  "lastname": "Chavez"
}

您可能想要更新该功能以更好地满足您的需求

jsfiddle:https ://jsfiddle.net/dapo/nwvpd4m2/

于 2019-11-06T16:29:11.020 回答