Search code examples
htmlvue.jsvuejs2

How to v-model 2 values?


I was using buefy <b-autocomplete> component and there is one property called v-model which is binding values to the input field

now I wanna bind Full Name into the field but the data consist with list[index].first_name and list[index].last_name, and the index is from a v-for loop.

Since v-model cannot bind a function (it has specific index so I cannot just concat it on computed then pass it on) so it's either v-model="list[index].first_name" or v-model="list[index].last_name"

How do I make it bind's these two?


Solution

  • You need a settable computed for full name, and you can v-model that. You just have to decide on a rule for where extra spaces go and what to do if there is no space.

    new Vue({
      el: '#app',
      data: {
        firstName: 'Joe',
        lastName: 'Smith'
      },
      computed: {
        fullName: {
          get() {
            return `${this.firstName} ${this.lastName}`;
          },
          set(newValue) {
            const m = newValue.match(/(\S*)\s+(.*)/);
    
            this.firstName = m[1];
            this.lastName = m[2];
          }
        }
      }
    });
    <script src="//unpkg.com/vue@latest/dist/vue.js"></script>
    <div id="app">
      First: {{firstName}}<br>
      Last: {{lastName}}<br>
      Full Name: <input v-model="fullName">
    </div>