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
相关产品推荐
相关产品推荐

