Search code examples
vue.jsvuetify.jsv-autocomplete

Vue.js v-autocomplete v-model new data


<v-autocomplete v-if="first.title == 'host'"
                :items="host"
                v-model="selected_host"
                item-value="host_n"
                outlined
                hide-details
                dense
              ></v-autocomplete>

I'd like to input new text which is not included in items.

autocomplete is just suggestion to user. But I can't input new data in v-autocomplete. Whenever I write new data, it was deleted.


Solution

  • You should use v-combobox (doc here) instead of v-autocomplete if you want the user to add its own value


    If you want to deal with multiple values, you can use the multiple attributes and passing an array to the v-model instead of a string (or an object if you use the return-object param)

    new Vue({
      el: '#app',
      vuetify: new Vuetify(),
      computed: {
        tagsSorted() {
          return this.tags.sort()
        }
      },
      data: () => ({
        host: [{
            host_n: 'Foo',
          },
          {
            host_n: 'Bar',
          }
        ],
        first: {
          title: 'host'
        },
        selected_host: ''
      }),
    
      methods: {
        sendData() {
          console.log(this.selected_host)
        }
      }
    })
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <script src="https://unpkg.com/[email protected]/dist/vuetify.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vuetify.min.css" />
    <div id="app" data-app>
      <v-combobox v-if="first.title == 'host'" :items="host" v-model="selected_host" item-value="host_n" item-text="host_n" outlined hide-details dense></v-combobox>
      <v-btn @click="sendData">Send data</v-btn>
    </div>