组件之间的双向绑定:v-model

🤍 前端开发工程师、技术日更博主、已过CET6

🍨 阿珊和她的猫_CSDN博客专家、23年度博客之星前端领域TOP1

🕠 牛客 高级专题作者、打造专栏《前端面试必备》《2024面试高频手撕题》《前端求职突破计划》

🍚 蓝桥云课 签约作者、上架课程《Vue.js 和 Egg.js 开发企业级健康管理项目》《带你从入门到实战全面掌握 uni-app》

文章目录

在Vue中,组件之间的双向绑定通常是通过使用 v-model 指令来实现的。在Vue3中,v-model 的使用方式有所变化,支持更灵活的自定义模型。

父组件向子组件传递数据

父组件可以通过 v-model 将数据传递给子组件,子组件通过 props 接收这些数据。

父组件

html 复制代码
<template>
<ChildComponent v-model="parentData" />
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
components: {
ChildComponent
},
setup() {
const parentData = ref('Hello from parent');
return { parentData };
}
};
</script>

子组件

html 复制代码
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>

<script>
export default {
props: {
modelValue: String // 注意这里使用的是 'modelValue' 而不是 'value'
},
emits: ['update:modelValue']
};
</script>

子组件向父组件传递数据

子组件可以通过 $emit 方法触发一个事件来更新父组件中的数据。

子组件

html 复制代码
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>

<script>
export default {
props: {
modelValue: String
},
emits: ['update:modelValue']
};
</script>

父组件

html 复制代码
<template>
<ChildComponent v-model="parentData" />
</template>

<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';

export default {
components: {
ChildComponent
},
setup() {
const parentData = ref('Hello from parent');
return { parentData };
}
};
</script>

自定义 v-model 的参数

Vue3 允许自定义 v-model 使用的 prop 和事件名。

父组件

html 复制代码
<template>
<CustomInput v-model="customValue" />
</template>

<script>
import { ref } from 'vue';
import CustomInput from './CustomInput.vue';

export default {
components: {
CustomInput
},
setup() {
const customValue = ref('');
return { customValue };
}
};
</script>

子组件

html 复制代码
<template>
<input :value="customProp" @input="$emit('customUpdate', $event.target.value)">
</template>

<script>
export default {
props: {
customProp: String // 自定义 prop 名称
},
emits: ['customUpdate'] // 自定义事件名称
};
</script>

在子组件中,你需要定义 emits 选项来声明自定义事件,并在模板中使用 $emit 来触发这些事件。

注意事项

  • 在Vue3中,v-model 默认使用 modelValue 作为 prop 名称,update:modelValue 作为事件名称。
  • 如果需要自定义 v-model 的 prop 或事件名称,可以在子组件中声明,并在父组件中使用自定义名称。
  • 双向绑定可能会导致数据流难以追踪,应谨慎使用,确保数据流单向化。

总结

v-model 是Vue中实现组件之间双向绑定的指令。在Vue3中,v-model 更加灵活,支持自定义 prop 和事件名称。通过 v-model,可以方便地在父组件和子组件之间同步数据。

相关推荐
Lovely_Ruby几秒前
前端er Go-Frame 的学习笔记:实现 to-do 功能(一)
前端·后端
用户841794814562 分钟前
如何使用 vxe-table 导出为带图片的单元格到 excel 格式文件
vue.js
脾气有点小暴6 分钟前
uniapp通用递进式步骤组件
前端·javascript·vue.js·uni-app·uniapp
问道飞鱼7 分钟前
【前端知识】从前端请求到后端返回:Gzip压缩全链路配置指南
前端·状态模式·gzip·请求头
小杨累了13 分钟前
CSS Keyframes 实现 Vue 无缝无限轮播
前端
小扎仙森14 分钟前
html引导页
前端·html
蜗牛攻城狮21 分钟前
JavaScript 尾递归(Tail Recursion)详解
开发语言·javascript·ecmascript
坐吃山猪30 分钟前
Electron04-系统通知小闹钟
开发语言·javascript·ecmascript
小飞侠在吗37 分钟前
vue toRefs 与 toRef
前端·javascript·vue.js
csuzhucong40 分钟前
斜转魔方、斜转扭曲魔方
前端·c++·算法