Home > other >  Vue.js Child Component not Updating Data in Parent Component
Vue.js Child Component not Updating Data in Parent Component

Time:04-30

I am using vue components in a Laravel project.

I have taken sample code from https://vuejs.org/guide/components/events.html#usage-with-v-model

I have a child component with an input box:

<script>
    export default {
    props: ['modelValue'],
   emits: ['update:modelValue']
}
</script>

<template>
  <input
   :value="modelValue"
   @input="$emit('update:modelValue', $event.target.value)"
 />
</template>

This component is being used in a parent component.

 <phone-input v-model="phone"/>  {{phone}}

The parent component displays the input box with the initial value of the phone variable. However, the changed value is not reflected in the parent's phone variable ( {{phone}} does not update). Am I missing something? I have cleared the cache, but it did not help.

I tried another variation of the code (from vue.js documentation code) as given here. However, this also does not work.

Parent
 <MyComponent v-model:title="bookTitle" />. {{bookTitle}}



<!-- Child Component MyComponent.vue -->
<script>
 export default {
 props: ['title'],
 emits: ['update:title']
 }
</script>

<template>
  <input
   type="text"
   :value="title"
   @input="$emit('update:title', $event.target.value)"
 />
</template>

Thanks for your help.

CodePudding user response:

<script>
    export default {
    props: ['modelValue'],
}
</script>

<template>
  <input
   :value="modelValue"
   @input="$emit('input', $event.target.value)"
 />
</template>

You need specially emit input to make it work

CodePudding user response:

Take a look at following snippet, looks ok:

const app = Vue.createApp({
  data() {
    return {
      phone: "0123456"
    }
  },
})
app.component('phoneInput', { 
  template: `
    <input
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
    />
  `,
  props: ['modelValue'],
  emits: ['update:modelValue'],
})

app.mount("#demo")
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
   <phone-input v-model="phone"></phone-input>
   {{ phone }}
</div>

  • Related