You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue 3+Nuxt.js中自定义输入组件v-model不生效问题求助

Vue 3 + Nuxt.js 自定义组件 v-model 绑定父组件数据不更新问题

在Vue 3结合Nuxt.js的项目中,使用自定义输入组件通过v-model绑定父组件的inputValue属性,但输入内容时该属性无法更新。相同代码在纯Vue 3项目中可正常运行,以下是相关代码:

自定义输入组件(MyInput.vue)

<template>
  <input
    type="text"
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
    :placeholder="placeholder"
    class="border border-gray-300 rounded-lg w-full p-2 text-black m-1"
  />
</template>

<script setup>
const props = defineProps({
  modelValue: String,
  placeholder: String,
});

const emit = defineEmits(["update:modelValue"]);
</script>

<script>
export default {
  name: "MyInput",
};
</script>

父组件代码

<template>
  <div>
    <MyInput v-model="inputValue" placeholder="Enter a value" />
  </div>
</template>

<script>
import MyInput from "./MyInput.vue";

export default {
  name: "MyParentComponent",
  components: {
    MyInput,
  },
  data() {
    return {
      inputValue: "",
    };
  },
};
</script>

可能的解决方案

  • 确认Nuxt版本兼容性:确保使用的是Nuxt 3(基于Vue 3)。如果是Nuxt 2,默认仅支持Vue 2,无法直接使用Vue 3的<script setup>语法,建议升级到Nuxt 3;若需保留Nuxt 2,需安装@nuxtjs/composition-api并配置,但<script setup>在Nuxt 2中支持有限。

  • 调整组件注册方式(Nuxt 3):Nuxt 3会自动注册components/目录下的组件,无需手动导入。移除父组件中的import MyInput和components配置项,直接使用<MyInput>即可。

  • 切换父组件为<script setup>写法:在Nuxt 3中推荐使用组合式API,将父组件改为以下写法,避免Options API可能的兼容性问题:

<template>
  <div>
    <MyInput v-model="inputValue" placeholder="Enter a value" />
    <p>当前输入值:{{ inputValue }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const inputValue = ref('')
</script>
  • 排查服务端渲染 hydration 问题:若控制台出现hydration不匹配警告,可使用<client-only>标签包裹自定义组件,确保仅在客户端渲染:
<client-only>
  <MyInput v-model="inputValue" placeholder="Enter a value" />
</client-only>

内容的提问来源于stack exchange,提问作者rvaidun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:05:25