[英]Emit value from child to parent component
In my Nuxt.js application, I try to emit a value from child to parent component.在我的 Nuxt.js 应用程序中,我尝试从子组件向父组件发出一个值。
The parent component is: pages/index.vue :父组件是: 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 :孩子是: 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我按照官方文档here
Related simple demo is hosted on Github.相关的简单演示托管在 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
.或者将它移到方法中的
methods
中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.