vue实现子组件向父组件传值的代码示例和父组件向子组件传值的代码示例
时间: 2023-06-22 07:33:26 浏览: 105
子组件向父组件传值的代码示例:
子组件:
```
<template>
<button @click="sendData">传递数据</button>
</template>
<script>
export default {
methods: {
sendData() {
this.$emit('send-data', 'Hello, 父组件!');
}
}
}
</script>
```
父组件:
```
<template>
<div>
<child-component @send-data="getData"></child-component>
<p>{{ message }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: ''
}
},
methods: {
getData(data) {
this.message = data;
}
}
}
</script>
```
父组件向子组件传值的代码示例:
父组件:
```
<template>
<div>
<child-component :message="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello, 子组件!'
}
}
}
</script>
```
子组件:
```
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
}
</script>
```
阅读全文