gpt4 book ai didi

javascript - 将值从子组件发送到父组件

转载 作者:行者123 更新时间:2023-12-02 22:16:29 26 4
gpt4 key购买 nike

在我的 Nuxt.js 应用程序中,我尝试从子组件向父组件发出一个值。

父组件是: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>

子级是: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>

当我单击“确定”按钮时,我没有获得更新的值。我缺少什么?

enter image description here屏幕截图显示,单击按钮时控制台不会记录新值,而是显示旧值。

我按照官方文档here

相关简单demo托管在 Github 上。

最佳答案

这一行是错误的:

v-on:input="$emit('input', value)"

这正在发出旧值。

应该是:

v-on:input="$emit('input', $event)"

这将发出新值。

或者您可以使用:

v-on:input="value => $emit('input', value)"

或者将其移出到methods中的方法。

关于javascript - 将值从子组件发送到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59369912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com