组件通信 父传子通信 子传父通信 兄弟通信实例
时间: 2023-09-05 11:07:41 浏览: 66
1. 父传子通信示例:
父组件:
```
<template>
<div>
<p>父组件数据:{{message}}</p>
<child-component :child-message="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
message: 'Hello World'
};
},
components: {
ChildComponent
}
};
</script>
```
子组件:
```
<template>
<div>
<p>子组件数据:{{childMessage}}</p>
</div>
</template>
<script>
export default {
props: ['childMessage']
};
</script>
```
2. 子传父通信示例:
父组件:
```
<template>
<div>
<p>父组件数据:{{message}}</p>
<child-component @update-message="updateMessage"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
message: ''
};
},
methods: {
updateMessage(value) {
this.message = value;
}
},
components: {
ChildComponent
}
};
</script>
```
子组件:
```
<template>
<div>
<input type="text" v-model="childMessage">
<button @click="updateParentMessage">发送消息</button>
</div>
</template>
<script>
export default {
data() {
return {
childMessage: ''
};
},
methods: {
updateParentMessage() {
this.$emit('update-message', this.childMessage);
}
}
};
</script>
```
3. 兄弟通信示例:
父组件:
```
<template>
<div>
<child-component1 @update-message="updateMessage"></child-component1>
<child-component2 :message="message"></child-component2>
</div>
</template>
<script>
import ChildComponent1 from './ChildComponent1.vue';
import ChildComponent2 from './ChildComponent2.vue';
export default {
data() {
return {
message: ''
};
},
methods: {
updateMessage(value) {
this.message = value;
}
},
components: {
ChildComponent1,
ChildComponent2
}
};
</script>
```
兄弟组件1:
```
<template>
<div>
<input type="text" v-model="childMessage">
<button @click="updateSiblingMessage">发送消息</button>
</div>
</template>
<script>
export default {
data() {
return {
childMessage: ''
};
},
methods: {
updateSiblingMessage() {
this.$emit('update-message', this.childMessage);
}
}
};
</script>
```
兄弟组件2:
```
<template>
<div>
<p>兄弟组件1传来的消息:{{message}}</p>
</div>
</template>
<script>
export default {
props: ['message']
};
</script>
```
阅读全文