Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 867
Travis Su Avatar asked May 09 '18 19:05

Travis Su


People also ask

When is the V-model evaluated?

The component data… The component data… The component data… By default, v-model is evaluated every time the input event is fired (ie. on keypress or paste.) If you’d rather wait until the user has finished inputting and unfocused the field, you can use the v-model.lazy modifier to have v-model listen to the change event instead.

What is V-model and how do I use it?

Similar to trim methods in most programming languages, the .trim modifier removes leading or trailing whitespace before returning the value. Alright, now that we know the basics of v-model inside of forms/inputs, let’s look at an interesting use for v-model – creating two-way data binding between components.

How do I use V-model multiple times for one component?

Using v-model multiple times for one component v-model is not limited to just one use per component. To use v-model multiple times we just have to be sure to name each prop uniquely and access it correctly inside our child component. Let’s add a second v-model to our input called lastName.

What is V-model in Vue?

Vue v-model is a directive that provides two-way data binding between an input and form data or between two components. It’s a simple concept in Vue development, but the true powers of v-model take some time to understand.


1 Answers

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>
like image 181
Roy J Avatar answered Sep 28 '22 06:09

Roy J