Vue ---父子组件之间互相传值与方法调用

本文介绍了一个简单的Vue.js应用实例,展示了如何实现父子组件之间的数据传递。通过具体代码示例,讲解了子组件如何向父组件发送消息以及父组件如何接收这些消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>组件的开发</title>
  <script src="../../lib/vue.min.js"> </script>
<link href="../../lib/bootstrap.min.css" rel="stylesheet">

</head>
<body>
     <!--父子组件之间传递内容,-->
    <div id="app">
<com1 v-bind:temp="msg" @fun="getMsg"></com1>
</div>
<template id="temp1">
<div>
<h1>一个元素,组件--{{temp}}</h1>
<input type="button" value="子组件想父组件传递内容" @click="sendMsg">
</div>
</template>

<script>
var com1 = {
template : '#temp1',
data (){
return {
sonmsg : '做一个孝顺的孩子,给爸爸200.'
};
},
props :[
'temp' ///子组件调用父组件的相关内容
],
methods :{
sendMsg(){
this.$emit('fun',this.sonmsg);
}
}

}

var vm = new Vue({
el : '#app',
data : {
msg : '这个是父组件的数据,爸爸有100块.你想要吗??',
msgformson : ''
},
methods : {
getMsg(data){
this.msgformson = data;
console.log(this.msgformson);
}
},
components :{
com1
}


});
</script>

</body>
</html>

### Vue.js 父子组件方法 #### 使用 Props 和 $emit 进行单向数据流通信 在Vue中,父子组件间的数据传递遵循单向下行流动的原则。父组件通过`props`向下传递数据至子组件,在此过程中可以传递任何类型的 JavaScript 数据结构,包括但不限于字符串、数、布尔、数组和对象[^2]。 对于子组件来说,如果需要父组件沟通,则通常会触发事件来通知父组件某些状态的变化或请求操作。这可通过`$emit()`函数实现,该函数允许子组件发射自定义事件并携带参数返回给监听这些事件的父级组件[^3]。 下面给出具体的代码示例: #### 示例:父组件向子组件发送消息并通过按钮点击反馈回数 ##### 子组件 (ChildComponent.vue) ```html <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) ```html <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"`,因此能够捕获到这条消息并更新自身的视图显示。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值