首页  >  文章  >  后端开发  >  Vue.js 给出 Props 概念

Vue.js 给出 Props 概念

Linda Hamilton
Linda Hamilton原创
2024-10-17 06:08:29830浏览

你好! Props 是 Vue.js 最需要的部分之一,它们允许组件之间交换信息。使用 props 是在 setup 函数内部完成的。以下是道具<脚本设置> 我们可以详细了解如何使用:

Vue.js da Props tushunchasi

  1. 定义道具: DefineProps 函数用于定义 Vue.js 中的 props。 DefineProps 对象用于定义 props 的类型和属性。
<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
  </div>
</template>

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

// Props-larni aniqlash
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  message: {
    type: String,
    default: 'Default message'
  }
})
</script>

这里的 props 对象定义了标题和消息属性。 title prop 类型是 String 且必需(required: true),message 具有 String 类型和默认值(Default message)。

  1. 使用道具: 通过defineProps函数定义的props可以直接放在
<template>
  <div>
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
  </div>
</template>

<script setup>
const props = defineProps({
  title: {
    type: String,
    required: true
  },
  message: {
    type: String,
    default: 'Default message'
  }
})

// Props-larni ishlatish
console.log(props.title)
console.log(props.message)
</script>
  1. 道具类型和验证: DefineProps 可用于定义 props 的类型和验证。在 Vue 3 中,我们可以提供用于验证的类型,例如 String、Number、Boolean、Array、Object ...
<script setup>
const props = defineProps({
  id: {
    type: Number,
    required: true
  },
  user: {
    type: Object,
    default: () => ({ name: 'Johon', age: 30 })
  }
})
</script>

在上面的示例中,id 属性是 Number 类型并且是强制的,而 user 属性是 Object 类型并且有一个默认值。

默认值允许您为 Vue 3 中的 props 定义预定义值。如果没有向组件发送任何 props,Vue 将使用默认值。这更方便,因为它使组件更易于使用且更安全。

在下一篇文章中,我们将讨论 Vue3 中的发射。

您可以在网络上关注我们,如果文章有用,请通过评论和 Vuechi 与您的朋友分享。 ?

以上是Vue.js 给出 Props 概念的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn