在Vue2和Vue3中,父子组件间的数据传递主要通过props向下传递(父传子)和自定义事件向上传递(子传父)。虽然基本原理相同,但在实现细节上,Vue3引入了Composition API带来了不同的写法。下面分别介绍两种版本的父子组件传参方式:
Vue2中的父子传参:
<!-- 父组件 -->
<template>
<ChildComponent :my-prop="parentValue" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentValue: 'Hello from Parent'
};
},
components: {
ChildComponent
}
};
</script>
•子组件通过props选项接收参数,并在模板或计算属性等地方使用。<!-- 子组件 -->
<script>
export default {
props: ['myProp'],
template: `
<div>{{ myProp }}</div>
`
};
</script>
2. 子传父:
•子组件触发一个自定义事件,向父组件传递数据。<!-- 子组件 -->
<script>
export default {
methods: {
sendDataToParent() {
this.$emit('customEvent', 'Data from child');
}
}
template: `
<button @click="sendDataToParent">Send Data</button>
`
};
</script>
•父组件监听并处理这个自定义事件。<!-- 父组件 -->
<template>
<ChildComponent @customEvent="handleCustomEvent" />
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
methods: {
handleCustomEvent(dataFromChild) {
console.log('Received data:', dataFromChild);
}
},
components: {
ChildComponent
}
};
</script>
Vue3中的父子传参:
1. 父传子:•使用defineProps声明子组件接收的props。<!-- 子组件 -->
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
myProp: String
});
</script>
<template>
<div>{{ props.myProp }}</div>
</template>
•父组件依然通过属性绑定来传递数据。<!-- 父组件 -->
<script setup>
import ChildComponent from './ChildComponent.vue';
const parentValue = ref('Hello from Parent');
</script>
<template>
<ChildComponent :my-prop="parentValue" />
</template>
2. 子传父:
•使用defineEmits声明子组件可以触发的自定义事件。<!-- 子组件 -->
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['customEvent']);
function sendDataToParent() {
emit('customEvent', 'Data from child');
}
</script>
<template>
<button @click="sendDataToParent">Send Data</button>
</template>
•父组件同样监听并处理这个自定义事件。<!-- 父组件 -->
<script setup>
import ChildComponent from './ChildComponent.vue';
function handleCustomEvent(dataFromChild) {
console.log('Received data:', dataFromChild);
}
</script>
<template>
<ChildComponent @customEvent="handleCustomEvent" />
</template>