在 Vue.js 中,父子组件之间的传参和事件调用是两个常见的通信方式。虽然 Vue 2 和 Vue 3 在这方面有一些差异,但总体概念和方法还是相似的。以下是 Vue 2 和 Vue 3 中父子组件传参和事件调用的基本用法。
Vue 2
父组件传参给子组件
在 Vue 2 中,父组件可以通过 props 向子组件传递数据。
父组件 (ParentComponent.vue):
<template>
<div>
<ChildComponent :message="parentMessage" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from Parent!'
};
}
};
</script>
子组件 (ChildComponent.vue):
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
};
</script>
子组件向父组件传递事件
在 Vue 2 中,子组件可以通过 $emit 触发父组件的方法。
父组件 (ParentComponent.vue):
<template>
<div>
<ChildComponent @custom-event="handleEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
methods: {
handleEvent(data) {
console.log('Event received from Child:', data);
}
}
};
</script>
子组件 (ChildComponent.vue):
<template>
<div>
<button @click="emitEvent">Click me</button>
</div>
</template>
<script>
export default {
methods: {
emitEvent() {
this.$emit('custom-event', 'Hello from Child!');
}
}
};
</script>
Vue 3
父组件传参给子组件
在 Vue 3 中,父组件仍然可以通过 props 向子组件传递数据。
父组件 (ParentComponent.vue):
<template>
<div>
<ChildComponent :message="parentMessage" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
import { ref } from 'vue';
export default {
components: {
ChildComponent
},
setup() {
const parentMessage = ref('Hello from Parent!');
return { parentMessage };
}
};
</script>
子组件 (ChildComponent.vue):
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: {
type: String,
required: true
}
}
};
</script>
子组件向父组件传递事件
在 Vue 3 中,子组件仍然可以通过 $emit 触发父组件的方法。
父组件 (ParentComponent.vue):
<template>
<div>
<ChildComponent @custom-event="handleEvent" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
setup() {
const handleEvent = (data) => {
console.log('Event received from Child:', data);
};
return { handleEvent };
}
};
</script>
子组件 (ChildComponent.vue):
<template>
<div>
<button @click="emitEvent">Click me</button>
</div>
</template>
<script>
export default {
emits: ['custom-event'],
setup(props, { emit }) {
const emitEvent = () => {
emit('custom-event', 'Hello from Child!');
};
return { emitEvent };
}
};
</script>
关键区别
-
组件定义:
- Vue 2 使用
data函数和methods对象。 - Vue 3 使用
setup函数和 Composition API。
- Vue 2 使用
-
Props 和 Emits 定义:
- Vue 2 在
props和$emit上直接定义。 - Vue 3 在
setup中使用props和emit参数。
- Vue 2 在
通过这些例子和解释,可以清楚地看到 Vue 2 和 Vue 3 中父子组件传参和事件调用的基本用法及其差异。