vue中父传子-子传父-非父子组件传值

vue中组件传值方式

父传子:通过v-bind的形式传值,子组件通过props接收。子组件的h2标签中的{{hello}}在页面上的展示为world。

**父组件:**
    <div class="home">
        <HelloWorld :hello="hello"/>
    </div>
    data(){
        return{
            hello: 'world'
        }
    }
    hr
    br
**子组件:**		
    <div class="hello">
        <h2>{{ hello }}</h2>
    </div>
    props: {
        hello: String
    }

子传父:通过$emit(" 事件 " , " 参数 ")的方式传值

**子组件**
<div class="hello">
    <h2 @click="handleClick">{{ hello }}</h2>
</div>
data(){
    return{
        info: '子组件传值给父组件'
    }
},
methods:{
    handleClick(){
        console.log("123")
        this.$emit("handleSon",this.info)
    }        
}
**父组件**
<div class="home">
    <HelloWorld :hello="hello" @handleSon="handleChange" />
</div>
methods:{
    handleChange(res){
        console.log(res)//在这里可以打印出“子组件传值给父组件”
    }
}

非父子组件传值:通过事件总线event bus进行传值。先创建一个bus.js,再main.js中引入。在两个兄弟组件中分别引入bus.js文件。发送方通过bus. e m i t ( " 事 件 名 " , 参 数 ) 发 送 , 接 收 方 在 m o u n t e d 生 命 周 期 钩 子 中 通 过 b u s . emit( " 事件名 " , 参数 )发送,接收方在mounted生命周期钩子中通过bus. emit("",)mountedbus.emit( “” , (res)=>{ console.log(res) })来接收。

两个兄弟组件
<div class="home">
    <HelloWorld :hello="hello" @handleSon="handleChange" />
    <HelloHao :hello="hello"  />
</div>
**兄弟组件--helloworld --发送方-----------------------------------------------------------**
<h2 @click="eventBus">事件总线</h2>
data(){
    return{
        info: '子组件传值给父组件',
        res: '事件总线'
    }
},
methods:{
    eventBus(){
        bus.$emit("eventWorld",this.res)
    }        
}
**兄弟组件--hellohao--接收方--------------------------------------------------------------**
mounted(){
    bus.$on("eventWorld",res=>{
        console.log(res)//在这里打印出“ 事件总线 ”
    })
}

另外bus.js代码

import Vue from 'vue'
var bus = new Vue();
export default bus

main.js代码中只需要加一行代码:Vue.prototype.bus = new Vue();即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值