vue3 在<script setup>中父子组件的传值
子组件向父组件传递数据
在Vue 3中,使用<script setup>
语法时,子组件向父组件传递数据通常涉及到两个步骤:首先,在子组件中定义要传递的数据和事件;其次,在父组件中通过定义的事件监听器接收这些数据。
子组件ChildComponent.vue
<script setup>
import { defineEmits, defineProps } from 'vue';
// 定义props
const props = defineProps({
someProp: String
});
// 定义要触发的事件
const emit = defineEmits(['updateParent']);
// 子组件的方法,用于触发事件并传递数据
function updateParentValue() {
emit('updateParent', newValue);
}
</script>
父组件parent.vue
<script setup>
import ChildComponent from './ChildComponent.vue';
// 定义接收数据的响应式引用
const childData = ref('');
// 处理子组件发出的事件,更新父组件的状态
const handleUpdateParent = (newValue) => {
childData.value = newValue;
};
</script>
<!-- 父组件模板 -->
<ChildComponent :someProp="childData" @updateParent="handleUpdateParent"></ChildComponent>
原文地址:https://blog.csdn.net/weixin_38483133/article/details/140628792
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!