在 Vue 3 中,父组件向子组件传值可以通过 props 实现。在子组件中,使用 'defineProps' 来声明 props,然后在 'setup' 函数中就可以直接使用了。

以下是一个简单的例子:

父组件:

<template>
  <ChildComponent :message='hello' />
</template>

<script>
import ChildComponent from './ChildComponent.vue'

export default {
  components: {
    ChildComponent
  },
  data() {
    return {
      hello: 'Hello World!'
    }
  }
}
</script>

子组件:

<template>
  <div>{{ message }}</div>
</template>

<script setup>
import { defineProps } from 'vue'

const props = defineProps({
  message: String
})
</script>

在子组件中,我们使用 'defineProps' 来声明 'message' 这个 prop,并且声明它的类型为字符串。在 'setup' 函数中,我们可以通过 'props' 对象来访问这个 prop 的值。

注意:在 Vue 3 中,使用 'setup' 函数来编写组件逻辑,而不是使用 'data'、'computed' 等选项。同时,在 'setup' 函数中,我们可以使用 Vue 3 的 Composition API 来编写组件逻辑。

Vue3 父组件向子组件传值:使用 script setup 和 defineProps

原文地址: https://www.cveoy.top/t/topic/mimS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录