1. 简答题 【利用父子组件通信完成】 创建页面如下图所示:  要求: 1、子组件中的标题、价格和开业大酬宾数据是通过父组件传递过来的 2、提交:代码截图和运行效果截图(代码截全)    提交 用Vue写
时间: 2024-10-24 10:12:04 浏览: 29
在Vue中,为了实现父组件向子组件传递数据并进行双向数据绑定以及响应式的父子通信,我们可以采用`props`属性和自定义事件。下面是一个简单的例子来满足你的需求。
首先,创建一个父组件Parent.vue:
```html
<template>
<div>
<child-component :title="parentTitle" :price="parentPrice" :eventMessage="eventMessage"></child-component>
<button @click="handleSubmit">提交</button>
</div>
</template>
<script>
export default {
components: { ChildComponent },
data() {
return {
parentTitle: '标题',
parentPrice: '价格',
eventMessage: '',
};
},
methods: {
handleSubmit() {
// 示例性的处理数据
this.eventMessage = `已提交:${this.parentTitle} - ${this.parentPrice}`;
},
},
};
</script>
```
然后,在子组件ChildComponent.vue中接收这些props,并可以触发自定义事件来通知父组件:
```html
<template>
<div>
<h3>{{ title }}</h3>
<p>价格:{{ price }}</p>
<!-- 使用v-on:custom-event 触发自定义事件 -->
<button v-on:submit-to-parent="handleCustomEvent">开业大酬宾</button>
</div>
</template>
<script>
export default {
props: {
title: String,
price: String,
},
methods: {
handleCustomEvent() {
this.$emit('submit-to-parent', this.price);
},
},
};
</script>
```
记得导入这两个组件到你的应用中,并确保它们关联正确。当用户点击"提交"按钮时,父组件会更新`eventMessage`,同时子组件通过自定义事件`submit-to-parent`将`price`传递给父组件。
运行效果截图无法直接展示,但在浏览器上预览上述代码,你会看到标题和价格会被动态显示,并且点击"开业大酬宾"按钮后会在父组件中看到相应的事件信息更新。
阅读全文