props/$emit
<template>
<div class="child">
<input type="text" v-model="message" @keyup="send" />
<p>收到来自父组件的消息:{{ messageFromParent }}</p>
</div>
</template>
<script>
export default {
name: 'Child',
props: ['messageFromParent'],
data() {
return {
message: '',
}
},
methods: {
send() {
this.$emit('on-receive', this.message)
},
},
}
</script>
<template>
<div class="parent">
<input type="text" v-model="message" />
<p>收到来自子组件的消息:{{ messageFromChild }}</p>
<Child :messageFromParent="message" @on-receive="receive" />
</div>
</template>
<script>
import Child from './child'
export default {
name: 'Parent',
data() {
return {
message: '',
messageFromChild: '',
}
},
components: {
Child,
},
methods: {
receive(msg) {
this.messageFromChild = msg
},
},
}
</script>
v-slot
<template>
<div class="child">
<h4>this is child component</h4>
<slot name="child"></slot>
</div>
</template>
<template>
<div class="parent">
<h3>this is parent component</h3>
<input type="text" v-model="message" />
<Child>
<template v-slot:child>
{{ message }}
</template>
</Child>
</div>
</template>
<script>
import Child from './child'
export default {
name: 'Parent',
data() {
return {
message: '',
}
},
components: {
Child,
},
}
</script>
refs/parent/children/root
<template>
<div class="child">
<h4>this is child component</h4>
<input type="text" v-model="message" />
<p>收到来自父组件的消息:{{ $parent.message }}</p>
</div>
</template>
<script>
export default {
name: 'Child1',
data() {
return {
message: '',
}
},
}
</script>
<template>
<div class="parent">
<h3>this is parent component</h3>
<input type="text" v-model="message" />
<p>收到来自子组件的消息:{{ child1.message }}</p>
<Child />
</div>
</template>
<script>
import Child from './child'
export default {
name: 'Parent',
data() {
return {
message: '',
child1: {},
}
},
components: {
Child,
},
mounted() {
this.child1 = this.$children.find((child) => {
return child.$options.name === 'Child1'
})
},
}
</script>
eventBus
export default class Bus {
constructor() {
this.callbacks = {}
}
$on(event, fn) {
this.callbacks[event] = this.callbacks[event] || []
this.callbacks[event].push(fn)
}\
$emit(event, args) {
this.callbacks[event].forEach((fn) => {
fn(args)
})
}
}
Vue.prototype.$bus = new Bus()
import Vue from 'vue'
export const Bus = new Vue()
mounted() {
this.$bus.$on('sendMessage', (obj) => {
const { sender, message } = obj
this.sender = sender
this.messageFromBus = message
})
},
methods: {
sendMessage() {
this.$bus.$emit('sendMessage', {
sender: this.$options.name,
message: this.message,
})
},
},