在 Vue 2 中,父组件向子组件传递数据通常使用 props,而子组件向父组件传递数据则通常使用事件。
父组件向子组件传递数据(props):
- 在父组件中,通过在子组件标签上绑定属性的方式传递数据,例如:
<!-- ParentComponent.vue -->
<template>
<ChildComponent :message="parentMessage" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentMessage: 'Hello from parent'
};
},
components: {
ChildComponent
}
};
</script>
- 在子组件中,通过 props 接收父组件传递的数据,例如:
<!-- ChildComponent.vue -->
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
props: {
message: String
}
};
</script>
子组件向父组件传递数据(事件):
- 在子组件中,通过 $emit 方法触发自定义事件,并将需要传递的数据作为参数传递,例如:
<!-- ChildComponent.vue -->
<template>
<button @click="sendMessageToParent">Send Message</button>
</template>
<script>
export default {
methods: {
sendMessageToParent() {
this.$emit('send-message', 'Hello from child');
}
}
};
</script>
- 在父组件中,通过监听子组件的自定义事件来接收子组件传递的数据,例如:
<!-- ParentComponent.vue -->
<template>
<ChildComponent @send-message="handleMessageFromChild" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
methods: {
handleMessageFromChild(message) {
console.log(message);
},
},
components: {
ChildComponent
}
};
</script>