vue中父子组件互相传值
时间: 2025-01-30 22:56:20 浏览: 30
Vue.js 父子组件传值方法
使用 Props 和 $emit 进行单向数据流通信
在Vue中,父子组件间的数据传递遵循单向下行流动的原则。父组件通过props
向下传递数据至子组件,在此过程中可以传递任何类型的 JavaScript 数据结构,包括但不限于字符串、数值、布尔值、数组和对象[^2]。
对于子组件来说,如果需要与父组件沟通,则通常会触发事件来通知父组件某些状态的变化或请求操作。这可通过$emit()
函数实现,该函数允许子组件发射自定义事件并携带参数返回给监听这些事件的父级组件[^3]。
下面给出具体的代码示例:
示例:父组件向子组件发送消息并通过按钮点击反馈回数
子组件 (ChildComponent.vue)
<template>
<div class="">
<h2>我是子组件</h2>
<!-- 显示来自父组件的消息 -->
<p>{{ messageFromParent }}</p>
<button @click="sendMessageToParent">向父组件传值</button>
</div>
</template>
<script>
export default {
props: ['messageFromParent'], // 接收父组件传来的内容
methods: {
sendMessageToParent() {
// 发射一个名为 'child-msg' 的事件并将当前计数器作为载荷发出
this.$emit('child-msg', "这是从子组件发来的问候");
}
}
}
</script>
父组件 (ParentComponent.vue)
<template>
<div id="parent">
<h1>这里是父组件</h1>
<!-- 向子组件传递信息,并绑定处理程序等待接收回应 -->
<child-component
:message-from-parent="'你好啊,子组件!'"
v-on:child-msg="handleMessage"
></child-component>
<hr />
<strong>收到的信息:</strong><span>{{ receivedMsg }}</span>
</div>
</template>
<script>
import ChildComponent from './components/ChildComponent';
export default {
name: 'Parent',
components: {
ChildComponent,
},
data() {
return {
receivedMsg: ''
};
},
methods: {
handleMessage(msg) {
console.log(`接收到子组件的消息: ${msg}`);
// 更新本地变量存储子组件传过来的新消息
this.receivedMsg = msg;
}
}
};
</script>
在这个例子中,当用户点击子组件内的按钮时,将会调用sendMessageToParent
方法,进而触发$emit('child-msg')
事件;与此同时,父组件已经绑定了相应的处理器v-on:child-msg="handleMessage"
,因此能够捕获到这条消息并更新自身的视图显示。
相关推荐


















