vue父子组件传值几种方法 具体代码
时间: 2023-09-04 16:15:45 浏览: 103
vue父子组件传值案例
1. 父组件向子组件传值,使用 props 属性
父组件:
```
<template>
<div>
<child-component :message="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello, World!'
}
}
}
</script>
```
子组件:
```
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: ['message']
}
</script>
```
2. 子组件向父组件传值,使用 $emit 方法
父组件:
```
<template>
<div>
<child-component @send-message="handleMessage"></child-component>
<p>{{ receivedMessage }}</p>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
receivedMessage: ''
}
},
methods: {
handleMessage(message) {
this.receivedMessage = message;
}
}
}
</script>
```
子组件:
```
<template>
<div>
<button @click="sendMessage">Send Message</button>
</div>
</template>
<script>
export default {
methods: {
sendMessage() {
this.$emit('send-message', 'Hello, World!');
}
}
}
</script>
```
3. 使用 provide/inject 传递数据
父组件:
```
<template>
<div>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
provide() {
return {
message: 'Hello, World!'
}
}
}
</script>
```
子组件:
```
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
inject: ['message']
}
</script>
```
阅读全文