Binding method result to v-model with Vue.js

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>

Leave a Comment