1、Props/emit(父子组件通信):
- 通过在父组件中使用
props
将数据传递给子组件。 - 子组件通过
$emit
触发事件,将数据传递回父组件。
<!– ParentComponent.vue –>
<template>
<child-component :dataProp=”parentData” @childEvent=”handleChildEvent” />
</template>
<script>
import ChildComponent from ‘./ChildComponent.vue’;
export default {
components: {
‘child-component’: ChildComponent
},
data() {
return {
parentData: ‘Hello from parent!’
};
},
methods: {
handleChildEvent(dataFromChild) {
console.log(‘Data received from child:’, dataFromChild);
}
}
};
</script>
<!– ChildComponent.vue –>
<template>
<div>
<p>{{ dataProp }}</p>
<button @click=”sendDataToParent“>Send Data to Parent</button>
</div>
</template>
<script>
export default {
props: {
dataProp: String
},
methods: {
sendDataToParent() {
this.$emit(‘childEvent‘, ‘Hello from child!’);
}
}
};
</script>