vue组件通信(父子传参)和数据绑定
时间: 2025-05-26 14:22:46 浏览: 5
### Vue 组件间的通信方式
#### 父子组件传参
在 Vue 中,父子组件之间可以通过 `props` 和 `$emit` 实现双向通信。
1. **父组件向子组件传递参数**
父组件通过 `props` 将数据传递给子组件。子组件声明需要接收的属性及其类型验证规则[^2]。
```html
<!-- 父组件 -->
<template>
<div>
<ChildComponent :message="parentMessage"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
data() {
return {
parentMessage: 'Hello from Parent!'
};
}
};
</script>
```
子组件接收到该参数并显示:
```html
<!-- 子组件 -->
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
};
</script>
```
2. **子组件向父组件传递参数**
子组件通过调用 `$emit` 方法触发自定义事件,并可携带参数回传到父组件。父组件监听此事件并对返回值作出响应[^1]。
```html
<!-- 子组件 -->
<template>
<button @click="sendToParent">Send to Parent</button>
</template>
<script>
export default {
methods: {
sendToParent() {
this.$emit('child-event', 'Data from child');
}
}
};
</script>
```
父组件绑定事件处理函数:
```html
<!-- 父组件 -->
<template>
<div>
<ChildComponent @child-event="handleEvent"></ChildComponent>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: { ChildComponent },
methods: {
handleEvent(data) {
console.log(data); // 输出 "Data from child"
}
}
};
</script>
```
---
#### 使用 `v-model` 进行数据绑定
Vue 提供了 `v-model` 指令用于简化表单输入和组件状态同步的过程。对于父子组件之间的交互,`v-model` 可以用来实现更简洁的数据绑定逻辑[^3]。
1. **基本用法**
当我们在一个组件上使用 `v-model` 时,默认会将其扩展为两个部分:一个是名为 `modelValue` 的 `prop`,另一个是名为 `update:modelValue` 的事件。
```html
<!-- 父组件 -->
<template>
<div>
<h1>Input Value: {{ inputValue }}</h1>
<CustomInput v-model="inputValue" />
</div>
</template>
<script>
import CustomInput from './CustomInput.vue';
export default {
components: { CustomInput },
data() {
return {
inputValue: ''
};
}
};
</script>
```
子组件内部实现如下:
```html
<!-- 子组件 -->
<template>
<input type="text" :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>
<script>
export default {
props: ['modelValue']
};
</script>
```
2. **自定义模型名称**
如果希望更改默认行为(即不使用 `modelValue`),可以在子组件中重新指定 `model` 属性[^4]。
```html
<!-- 子组件 -->
<template>
<input type="text" :value="customProp" @input="$emit('update', $event.target.value)">
</template>
<script>
export default {
props: ['customProp'],
model: {
prop: 'customProp',
event: 'update'
}
};
</script>
```
对应的父组件代码调整为:
```html
<!-- 父组件 -->
<template>
<div>
<CustomInput v-model="customValue" />
</div>
</template>
<script>
import CustomInput from './CustomInput.vue';
export default {
components: { CustomInput },
data() {
return {
customValue: ''
};
}
};
</script>
```
---
### 总结
以上展示了如何利用 `props`、`$emit` 和 `v-model` 来完成 Vue 组件间的数据流动与绑定操作。这些机制使得开发者能够灵活地构建模块化应用结构,同时保持清晰的状态管理边界。
阅读全文
相关推荐


















