子組件調用父變數 - daniel-qa/Vue GitHub Wiki

子組件調用父變數

  • Parent.vue(父组件)
<template>
    <div>
        <h2>父组件</h2>
        <Child :msg="message" />
    </div>
</template>

<script setup>
import Child from "./Child.vue";

const message = "Hello, 子组件!";
</script>
  • Child.vue(子组件)
<template>
    <h3>子组件收到的消息: {{ msg }}</h3>
</template>

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

// 接收父组件传递的变量
const props = defineProps({
    msg: String
});
</script>

變數前面要不要加 props.

在 setup 中, 不一定 需要加 props,可以直接使用解构的方式来获取 msg。但如果你不解构,默认会通过 props.msg 来访问。

两种方式:

  • 1 使用 props(需要加 props)
<script setup>
import { defineProps } from "vue";

const props = defineProps({
    msg: String
});

console.log(props.msg);  // 需要通过 `props.msg` 访问
</script>
  • 2 解构 props(不需要加 props)
<script setup>
import { defineProps } from "vue";

// 直接解构 `msg`,不需要再加 `props` 前缀
const { msg } = defineProps({
    msg: String
});

console.log(msg);  // 直接使用 `msg`
</script>
⚠️ **GitHub.com Fallback** ⚠️