[toc]
父子组件的传值通信
父组件向子组件传值
父组件:
<template> <child :message="parentMessage"></child> </template> data () { return { parentMessage: "this is a message from parent" } }
子组件:
<template> <p>{{message}}</p> </template>/* 一般形式 */data () { props: ["message"] }/* 指定接收类型 */data () { props: { message: { type: String, //接收类型 default: "this is the default value" // 默认值 } } }
子组件向父组件传值
Note 子组件不能直接更改父组件中的内容,因此可以通过子组件触发事件来传值给父组件。
父组件:
<template> <div class="root"> /* 自动监听子组件注册的 getChildValue 事件*/ <child @getChildValue="receive"></child> <p>{{valueFromChild}}</p> </div></template>data () { return { valueFromChild: "defaultValue" } }, methods: { receive (valueFromChild) { this.valueFromChild = valueFromChild } }
子组件:
<template> <button @click="sendValueToParent">click to send value to parent</button> </template> data () { return { childValue: 'this is child Value' } }, methods: { sendValueToParent () { /* 将 childValue 传递给父组件 */ this.$emit('getChildValue', this.childValue) } }
非父子组件之间的传值通信
创建
eventBus.js
import Vue from 'vue'var bus = new Vue()export default bus
组件 A
<template> <div class="root"> <button @click="sendMessageToB">click here to send a message to B</button> </div></template>import eventBus from '.../eventBus.js' data () { return { message: "message from A" } }, methods: { sendMessageToB () { eventBus.$emit('transfer', this.message); } }
组件 B
<template> <div class="root">{{messageFromA}}</div> </template> import eventBus from '.../eventBus.js'data () { return { messageFromA: "defaultValue" } },created () { eventBus.$on('transfer', function (message) { this.messageFromA = message }) }
作者:沙海飞鱼
链接:https://www.jianshu.com/p/75ff1773ce41
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)