vue实现发送值接受值
父子组件通信
在Vue中,父子组件通信可以通过props和自定义事件实现。父组件通过props向子组件传递数据,子组件通过$emit触发事件向父组件传递数据。
父组件向子组件传递数据:
<template>
<child-component :message="parentMessage" @update="handleUpdate"></child-component>
</template>
<script>
export default {
data() {
return {
parentMessage: 'Hello from parent'
}
},
methods: {
handleUpdate(newValue) {
this.parentMessage = newValue
}
}
}
</script>
子组件接收和发送数据:
<template>
<div>
<p>接收到的消息: {{ message }}</p>
<button @click="sendMessage">发送消息给父组件</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
sendMessage() {
this.$emit('update', 'Hello from child')
}
}
}
</script>
非父子组件通信
对于非父子组件间的通信,可以使用事件总线或Vuex状态管理。
使用事件总线:

// eventBus.js
import Vue from 'vue'
export const EventBus = new Vue()
// 组件A发送事件
EventBus.$emit('custom-event', data)
// 组件B接收事件
EventBus.$on('custom-event', data => {
console.log(data)
})
Vuex状态管理
对于大型应用,推荐使用Vuex进行状态管理。
定义store:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
sharedValue: ''
},
mutations: {
updateValue(state, newValue) {
state.sharedValue = newValue
}
},
actions: {
setValue({ commit }, value) {
commit('updateValue', value)
}
}
})
组件中使用:

<template>
<div>
<p>共享值: {{ sharedValue }}</p>
<input v-model="localValue" @input="updateStore">
</div>
</template>
<script>
export default {
computed: {
sharedValue() {
return this.$store.state.sharedValue
}
},
data() {
return {
localValue: ''
}
},
methods: {
updateStore() {
this.$store.dispatch('setValue', this.localValue)
}
}
}
</script>
provide/inject
对于深层嵌套组件,可以使用provide/inject。
祖先组件:
export default {
provide() {
return {
sharedData: this.sharedData
}
},
data() {
return {
sharedData: 'Some shared data'
}
}
}
后代组件:
export default {
inject: ['sharedData'],
mounted() {
console.log(this.sharedData) // 输出: Some shared data
}
}






