vue3 组件传值 (父传子、子传父、父拿子的值)

742 阅读1分钟

defineProps

父传子

父组件

<template>
  <div>
    <Child :msg="msg" />
  </div>
</template>

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

const msg = ref("父传子");
</script>

子组件

<template>
  <div>child</div>
</template>

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

const props = defineProps({
  msg: {
    type: String,
    default: "",
  },
});

console.log("props", props); // Proxy {mag: ‘父传子’}
</script>

defineEmits

子传父

子组件

<template>
  <div @click="handleClick">child</div>
</template>

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

const emits = defineEmits(["get"]);

const handleClick = () => {
  emits("get", "子传父");
};
</script>

父组件

<template>
  <div>
    <Child @get="getFn" />
  </div>
</template>

<script lang="ts" setup>
import Child from "./child.vue";

const getFn = (e: string) => {
  console.log("e", e); // 子传父 
};
</script>


defineExpose

父拿子的值

父组件

<template>
  <div>
    <Child ref="childRef" />
    <div @click="handleClick">获取子组件的值</div>
  </div>
</template>

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

const childRef = ref(null);

const handleClick = () => {
  console.log(childRef.value.msg); // 'hello'
};
</script>

子组件

<template>
  <div>child</div>
</template>

<script lang="ts" setup>
import { defineExpose, ref } from "vue";

const msg = ref("hello");

defineExpose({
  msg,
});
</script>