在vue3的语法中,父子页面传参与vue2的写法有些许不同
父子传参的写法如下:
父页面:
<template>
<ChildComponent :parentData="parentData" @childEvent="handleChildEvent" />
</template>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const parentData = ref('这是父组件的数据');
const handleChildEvent = (value) => {
console.log('来自子组件的事件:', value);
};
</script>
子页面:
<template>
<div>
<p>来自父组件的数据:{{ parentData }}</p>
<button @click="sendToParent">点击向父组件发送事件</button>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
parentData: {
type:Stribg,
required:true
}
});
const emit = defineEmits(['childEvent']);
const sendToParent = () => {
emit('childEvent', '这是来自子组件的事件');
};
</script>
在子页面的方法使用父页面传的参数时,直接写props.parentData就可以。
这样就实现父子传参了。
1040

被折叠的 条评论
为什么被折叠?



