vue3中的父子组件传值

一:子组件调用父组件的方法

1.父组件

<template>
  <p>{{ count }}</p>
  <Child
    :count="count"
    @changeCount="changeCount"
  ></Child>
</template>

<script lang="ts" setup>
import Child from "./Child.vue";
import {ref} from "vue";

const count = ref(1)
const changeCount = (val) => {
  count.value = val
}
</script>

2.子组件

<template>
  <p>父组件传来的值:{{ count }}</p>
  <button @click="changeCount">改变父组件的count</button>
</template>

<script lang="ts" setup>
import {defineProps, defineEmits} from "vue";

// 1.接收父组件传来的值:
const props = defineProps(["count"]);

// 2.定义一个变量来接收父组件传来的方法
const emit = defineEmits(["changeCount"]);
const changeCount = () => {
  emit("changeCount", 5)
}
</script>

接收父组件传来的值:(四种方式)

// 方式一
const props = defineProps(["count"]);

// 方式二:可以设置传来值的类型
const props = defineProps({
  count: Number,
})

// 方式三:可以设置传来值的类型、默认值
const props = defineProps({
  count: {
    type: Number,
    default: 0
  }
})

// 方式四:可以设置传来值的多种类型
const props = defineProps({
  count: [Number, String],
})

二:父组件调用子组件的方法

1.父组件

<template>
  <Child ref="childRef"/>
  <button @click="handleClick">提交</button>
</template>

<script lang="ts" setup>
import {ref} from "vue";
import Child from "./Child.vue";

const childRef = ref(null);
const handleClick = () => {
  // 获取到子组件的数据
  let title = childRef.value.test.title;
  
  // 调用子组件的方法
  childRef.value.submit('aa');
};

</script>

2.子组件

<template>
  <p>{{ test.title }}</p>
</template>

<script lang="ts" setup>
import {reactive} from "vue";

const test = reactive({
  title: "标题",
});

const submit = (val) => {
  test.title = val || "你调用了子组件的方法";
};

defineExpose({
  test,
  submit
});

</script>