Vue3 中,父子组件如何传递参数?(vue父子组件传递数据方法)
在 Vue3 中,组件化开发是非常重要的特征,那么组件之间传值就是开发中常见的需求了。组件之间的传值三种方式:父传子、子传父、非父子组件传值。
一、父传子( defineProps )
父组件主要通过使用 props 向子组件传值。
在使用 <script setup> 的单文件组件中,props 可以使用 defineProps() 、defineEmits() 宏来声明:
在父组件( Parent.vue )中,向子组件传值:
<template>
<Child :message="parentMessage" />
</template>
<script setup>
import Child from './Child.vue'
const parentMessage= 'Hello Parent';
</script>
在子组件( Child.vue )中,接收父组件( Parent.vue )的参数:
<template>
<div>{{ message }}</div>
</template>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
message: String
});
</script>
二、子传父( defineEmits )
在子组件( Child.vue )中,向父组件( Parent.vue )的传值:
<template>
<button @click="setData">Click me</button>
</template>
<script setup>
import { defineEmits } from 'vue';
const emit = defineEmits(['update']);
function setData() {
emit('update', 'Hello Child');
}
</script>
在父组件( Parent.vue )中,接收子组件( Child.vue )的参数:
<template>
{{ messageChild }}
<Child @update="handleMessage" />
</template>
<script setup>
import Child from './Child.vue';
import { ref } from 'vue';
const messageChild = ref('Hello');
function handleMessage(msg) {
messageChild.value = msg;
}
</script>
相关文档链接:
props文档:
https://cn.vuejs.org/guide/components/props.html