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

Vue3组合式API:如何同时实现输入值从Props和用户输入更新?

Vue输入框Props与双向绑定问题解决方案

问题描述

  • 使用ref绑定输入框时,输入值无法随父组件传入的Props同步更新
  • 使用toRef绑定Props到输入框时,输入框无法响应用户的输入操作
  • 尝试过watch、computed方案,均未解决上述问题

解决方案

通过引入内部响应式变量,结合watch监听Props变化,实现输入框值的双向同步:

<template>
    <input
        v-model="inputVal"
        @change="$emit('change-val', inputVal)"
        type="text"
    >
</template>

<script>
import { ref, toRef, watch } from 'vue'

export default {
    name: 'RefInput',
    props: {
        val: [String, Number, Array]
    },
    setup(props) {
        const propsVal = toRef(props, 'val')
        const inputVal = ref(propsVal.value)

        watch(propsVal, (newVal) => {
            inputVal.value = newVal
        })

        return {
            inputVal
        }
    }
}
</script>

实现原理

  • 用toRef创建Props中val的响应式引用,确保能监听到其变化
  • 定义内部响应式变量inputVal绑定到输入框,保证用户输入能触发响应式更新
  • 通过watch监听Props值的变更,将新值同步到内部变量,实现父组件Props更新时输入框值同步
  • 输入框值改变时通过$emit向父组件传递新值,完成双向绑定的闭环

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:37:14