vue 组件的三种传值方式

本文介绍了Vue.js中三种常见的组件间通信方式:父组件向子组件传递数据、子组件向父组件发送事件以及平行组件间的通信。通过实例展示了如何使用props、$emit和空的Vue对象实现这些通信。

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

一、父传子

关键词:添加属性 props

<body>
<div id="edd">
<v-fa></v-fa>
<v-box> </v-box>
</div>

<template id="father">
<div>
<p>{{str}}</p>
<button @click='tap'>向子组件传值</button>
<hr/>
<v-child :name='str1'></v-child>
</div>
</template>

<template id="child">
<div>
<p>{{this.name}}</p>

</div>
</template>

</body>
<script>
var vm = new Vue({
el:'#edd',
components:{
'v-fa':{
template:'#father',
data:function(){
return {
str:'我是父组件',
str1:''
}
},
methods:{
tap(){
this.str1=this.str
}
},
components:{
'v-child':{
props:['name'],
template:'#child',
data:function(){
return{}
}
}
}
},
}
})
</script>


二、子传父

关键词:$emit   定义方法

<body>
<div id="out">
<v-father></v-father>
</div>

<template id="father">
<div>
<h1>father------{{str}}</h1>
<hr>
<v-child @to-parent="getdata"></v-child>

</div>
</template>

<template id="child">
<div>
<h1>childr-------{{str}}</h1>
</div>
</template>
</body>

<script>
var vm = new Vue({
el:'#out',
components:{
'v-father':{
template:'#father',
data(){
return{
str:''
}
},
methods:{
getdata(msg){
this.str = msg
}
},
components:{
'v-child':{
template:'#child',
data(){
return{
str:'this is child'
}
},
created(){
this.$emit('to-parent',this.str)
}
}
}
}
}
})
</script>


三、平行组件传值

关键词:$emit  $on  空的vue对象

<body>
<div id="app">
<v-a></v-a>
<hr>
<v-b></v-b>
</div>
<template id="a">
<div>

this is a {{str}}

<button @click='tap'>send</button>

</div>
</template>

<template id="b">
<div>
this is b {{str}}
</div>
</template>
</body>
<script>
var vm1 = new Vue()

var vm = new Vue({
el:'#app',
components:{
'v-a':{
template:'#a',
data(){
return {
str:'this is a ,need to b'
}
},
methods:{
tap(){
vm1.$emit("isa",this.str)
}
}

},
'v-b':{
template:'#b',
data(){
return{
str:''
}

},
mounted(){
var _this = this;
vm1.$on("isa",function(msg){
_this.str = msg
})
}
}
}

})
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值