// 父组件
<template>
<div class="parent">
<h2>父组件</h2>
<child-component :message="parentMsg" @child-event="handleChildEvent"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentMsg: 'Hello Vue!'
};
},
components: {
'child-component': ChildComponent
},
methods: {
handleChildEvent(e) {
console.log(`接收到子组件的事件:${e}`);
}
}
};
</script>
// 子组件
<template>
<div class="child">
<h3>子组件</h3>
<p>从父组件传递过来的消息:{{ message }}</p>
<button @click="emitEvent">触发事件</button>
</div>
</template>
<script>
export default {
props: ['message'],
methods: {
emitEvent() {
this.$emit('child-event', 'Hello from child component!');
}
}
};
</script>本文介绍了Vue.js中组件与数据传递的最佳实践。在父组件中,将消息作为数据通过props传递给子组件,并在子组件中通过props接收。父组件中使用子组件时,可以通过绑定属性的方式将数据传递给子组件。在子组件中,可以使用props属性接收父组件传递过来的数据,并在模板中使用插值语法展示。
子组件可以通过$emit方法触发自定义事件,并将数据传递给父组件。在父组件中,通过在子组件上监听对应的事件,可以接收到子组件触发的事件,从而进行相应的处理。通过这种方式,可以实现父子组件之间的双向通信。
综上所述,合理使用props进行父子组件之间的数据传递,并通过自定义事件实现双向通信,是Vue.js组件开发中的最佳实践。