在 Vue 3 中,props 是用于父组件向子组件传递数据的一种机制

以下是如何在 Vue 3 的 Composition API 中使用 props 的步骤:

  1. 定义组件并声明 props

首先,你需要在子组件中声明 props。这可以通过在组件的 <script> 标签内使用 defineProps 函数来完成。

html 复制代码
<template>  
  <div>  
    {{ message }}  
  </div>  
</template>  
  
<script setup>  
import { defineProps } from 'vue';  
  
const props = defineProps({  
  message: {  
    type: String,  
    required: true,  
    default: 'Hello from props!'  
  }  
});  
</script>

在这个例子中,我们定义了一个名为 messageprop,并指定了它的类型为 String。我们还设置了 required 属性为 true,表示这个 prop 是必须的,并为其提供了一个默认值 'Hello from props!'

  1. 在父组件中使用子组件并传递 props

接下来,在父组件中,你可以像平常一样使用子组件,并通过属性 (attributes) 的方式传递 props

html 复制代码
<template>  
  <ChildComponent :message="parentMessage" />  
</template>  
  
<script setup>  
import { ref } from 'vue';  
import ChildComponent from './ChildComponent.vue';  
  
const parentMessage = ref('Hello from parent!');  
</script>
  1. 在子组件中使用 props

在子组件的 setup 函数中,通过 defineProps 定义的 props 可以直接作为变量使用。在我们的例子中,message prop 可以在模板中直接通过 {``{ message }} 访问,也可以在 setup 函数内的其他逻辑中使用。

确保你已经安装了 Vue 3,并且你的项目配置正确地支持了 Vue 3 的 Composition API 和 <script setup> 语法。<script setup> 是 Vue 3 的一个新特性,它允许你在 <script> 标签内直接编写 Composition API 的代码,而无需显式地导出任何东西。这大大简化了组件的编写过程。

相关推荐
white-persist几秒前
轻松抓包微信小程序:Proxifier+Burp Suite教程
前端·网络·安全·网络安全·微信小程序·小程序·notepad++
敲敲了个代码1 小时前
多标签页强提醒不重复打扰:从“弹框轰炸”到“共享待处理队列”的实战
java·前端·javascript·面试·架构
不想上班只想要钱2 小时前
动态类名在 <swiper-slide 的复制项中没有起作用的解决方法
前端·vue.js
weixin_395448912 小时前
tidl_import_mul_rmfsd_psd_u8_3x480x544_bise_raw_dynamic.txt
java·服务器·前端
多多*2 小时前
图解Redis的分布式锁的历程 从单机到集群
java·开发语言·javascript·vue.js·spring·tomcat·maven
Jinuss3 小时前
源码分析之React中updateContainerImpl方法更新容器
前端·react.js·前端框架
Mr Xu_3 小时前
Vue + Element Plus 实现前端导出 Excel 功能详解
前端·javascript·vue.js
前端大波3 小时前
vue3的自动化路由(unplugin-vue-router)
javascript·vue.js·自动化
仰泳之鹅3 小时前
【杂谈】使用Edge浏览器下载文件显示“Microsoft Defender SmartScreen 已阻止此不安全文件”的解决方法
前端·edge
万邦科技Lafite3 小时前
小红书评论数据一键获取,item_reviewAPI接口讲解
大数据·前端·数据库·chrome·电商开放平台