In my Nuxt.js application, I try to emit a value from child to parent component.
The parent component is: pages/index.vue :
<template>
<div>
<custom-input v-model="value" />
<v-btn @click="showValue">
Ok
</v-btn>
</div>
</template>
<script>
import CustomInput from '@/components/CustomInput.vue'
export default {
components: { CustomInput },
data () {
return {
value: 'hello'
}
},
watch: {
value (val) {
console.log('value' + val)
}
},
methods: {
showValue () {
console.log('value is: ' + this.value)
}
}
}
</script>
The child is: component/CustomInput.vue :
<template>
<v-text-field
v-bind:value="value"
v-on:input="$emit('input', value)"
/>
</template>
<script>
export default {
name: 'CustomInput',
props: {
value: {
type: String,
required: true
}
},
watch: {
value () {
this.$emit('input', this.value)
}
}
}
</script>
When I click on the button Ok, I am not getting the updated value. What am I missing ?
Screenshot shows the new value is not console logged on a button click, instead the old one is displayed.
I followed the official documentation here
Related simple demo is hosted on Github.
This line is wrong:
v-on:input="$emit('input', value)"
This is emitting the old value.
It should be:
v-on:input="$emit('input', $event)"
This will emit the new value.
Alternatively you could use:
v-on:input="value => $emit('input', value)"
Or move it out to a method in methods
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.