Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding method result to v-model with Vue.js

Tags:

vue.js

How do you bind a method result to a v-model with Vue.js?

example :

<someTag v-model="method_name(data_attribute)"></someTag> 

I can't make it work for some reason.

Thank you.

like image 990
greenymaster69 Avatar asked Feb 04 '16 20:02

greenymaster69


People also ask

What does V-bind do in Vue?

In Vue, v-bind lets you bind an HTML attribute to a JavaScript expression. There are two broad use cases for this one-way data binding: Binding to built-in attributes, like href or class. Passing props to a child component.

How does V-model work in Vue?

Vue v-model is a directive that creates a two-way data binding between a value in our template and a value in our data properties. A common use case for using v-model is when designing forms and inputs. We can use it to have our DOM input elements be able to modify the data in our Vue instance.

Does Vue have data binding?

Vue provides its own set of directives used to dynamically bind our data to the templates. Text Binding: It is used when we need to bind the content of any HTML in Vue. The syntax for using text binding is by using the v-text directive in any HTML element and a data property should be assigned to it.


2 Answers

Years later, with more experience, I found out that is it easier to bind :value instead of using v-model. Then you can handle the update by catching @change.

Edit (per request):

<input :value="myValue" @change="updateMyValue">  ...  methods: {   updateMyValue (event) {     myValue = event.target.value.trim() // Formatting example   } } 

And in a child component:

// ChildComponent.vue  <template>   <button     v-for="i in [1,2,3]">     @click="$emit('change', i) /> </template>  // ParentComponent.vue  <template>   <child-component @change="updateMyValue" /> </template>  <script> import ChildComponent from './child-component'  export default {   components: {     ChildComponent   },   data () {     return {       myvalue: 0     }   },   methods: {     updateMyValue (newValue) {       this.myvalue = newValue     }   } } </script> 
like image 168
greenymaster69 Avatar answered Oct 13 '22 15:10

greenymaster69


v-model expressions must have a get and set function. For most variables this is pretty straight forward but you can also use a computed property to define them yourself like so:

data:function(){     return { value: 5 } }, computed: {     doubleValue: {         get(){             //this function will determine what is displayed in the input             return this.value*2;         },         set(newVal){             //this function will run whenever the input changes             this.value = newVal/2;         }     } } 

Then you can use <input v-model="doubleValue"></input>

if you just want the tag to display a method result, use <tag>{{method_name(data_attribute)}}</tag>

like image 43
Jeff Avatar answered Oct 13 '22 15:10

Jeff