>[success] # defineProps
`defineProps` 作為編譯器宏幾個用法特點
* 不需要被導入即可使用,它會在編譯`<script setup>`語法塊時一同編譯掉
* 只能在`<script setup>`中使用
* 接收與`props`選項相同的值
* 必須在`<script setup>`的頂層使用,不可以在`<script setup>`的局部變量中引用。
* `defineProps()`宏中的參數不可以訪問`<script setup>`中定義的其他變量,因為在編譯時整個表達式都會被移到外部的函數中。
1. 不需要被導入即可使用,它會在編譯`<script setup>`語法塊時一同編譯掉
~~~html
<template> {{ props.name }} </template>
<!--在頁面可以直接使用。但注意僅限頁面-->
<template> {{ name }} </template>
<script setup>
// 無需導入直接使用
const props = defineProps({
name: String,
});
</script>
<style></style>
~~~
2. 接收與`props`選項相同的值
~~~ html
<template> {{ props.name }} </template>
<script setup>
import props from '../Props/props';
// const props = defineProps(['name']);
/**
* 支持配置字段 type 類型,required 是否必填,default默認值,validator 校驗
* interface PropOptions<T> {
* type?: PropType<T>
* required?: boolean
* default?: T | ((rawProps: object) => T)
* validator?: (value: unknown) => boolean
* }
*
*/
// const props = defineProps({ name: String }); // 設置類型
const props = defineProps({
name: {
type: String,
require: true,
default: '1',
validator: (value) => {
return value.length > 1;
},
},
});
</script>
<style></style>
~~~
3. 必須在`<script setup>`的頂層使用,不可以在`<script setup>`的局部變量中引用。
~~~html
<template> {{ a.name }} </template>
<script setup>
// 報錯不能在局部變量中使用:ReferenceError: defineProps is not defined
function aFun() {
const props = defineProps({
name: {
type: String,
require: true,
default: '1',
validator: (value) => {
return value.length > 1;
},
},
});
return props;
}
const a = aFun();
</script>
<style></style>
~~~
4. `defineProps()` 宏中的參數不可以訪問 `<script setup>` 中定義的其他變量,因為在編譯時整個表達式都會被移到外部的函數中。
~~~html
<template> {{ props.name }} </template>
<script setup>
const len = 1;
const props = defineProps({
name: {
type: String,
require: true,
default: '1',
validator: (value) => {
// 報錯 `defineProps` are referencing locally declared variables
return value.length > len;
},
},
});
</script>
<style></style>
~~~
5. 只能在`<script setup>`中使用
* 在其他文件聲明了一個`defineProps`
~~~
import { defineProps } from 'vue';
export default defineProps({
name: {
type: String,
require: true,
default: '1',
validator: (value) => {
return value.length > 1;
},
},
});
~~~
* 使用報錯
~~~html
<template>
<div>測試</div>
<children :name="1" />
</template>
<script setup>
// 警告defineProps() is a compiler-hint helper that is only usable inside <script setup> of a single file component. Its arguments should be compiled away and passing it at runtime has no effect.
import children from './components/children.vue';
</script>
<style></style>
~~~
>[danger] ##### 其他配置項
1. 所有 prop 默認都是可選的,除非聲明了`required: true`。

2. 未傳遞的 prop 會有一個缺省值`undefined`
3. 如果聲明了`default`值,那么在 prop 的值被解析為`undefined`時,無論 prop 是未被傳遞還是顯式指明的`undefined`,都會改為`default`值。
4. 聲明多類型
~~~
defineProps({
disabled: [Boolean, Number]
})
~~~
5. 可以檢測的類型,`String` `Number` `Boolean` `Array` `Object` `Date` `Function` `Symbol` `自定義類`
* 自定義類舉例子
~~~
class Person {
constructor(firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
defineProps({
author: Person
})
~~~
>[danger] ##### 使用技巧
1. **prop 被用于傳入初始值;而子組件想在之后將其作為一個局部數據屬性。** 在這種情況下,最好是新定義一個局部數據屬性,從 prop 上獲取初始值即可:
~~~
const props = defineProps(['initialCounter'])
// 計數器只是將 props.initialCounter 作為初始值
// 像下面這樣做就使 prop 和后續更新無關了
const counter = ref(props.initialCounter)
~~~
2. **prop 以原始的形式傳入,但還需作轉換。** 在這種情況中,最好是基于該 prop 值定義一個計算屬性:
~~~
const props = defineProps(['size'])
// 該 prop 變更時計算屬性也會自動更新
const normalizedSize = computed(() => props.size.trim().toLowerCase())
~~~
>[info] ## 官網
[Props](https://cn.vuejs.org/guide/components/props.html)
- 官網給的工具
- 聲明vue2 和 vue3
- 指令速覽
- Mustache -- 語法
- v-once -- 只渲染一次
- v-text -- 插入文本
- v-html -- 渲染html
- v-pre -- 顯示原始的Mustache標簽
- v-cloak -- 遮蓋
- v-memo(新)-- 緩存指定值
- v-if/v-show -- 條件渲染
- v-for -- 循環
- v-bind -- 知識
- v-bind -- 修飾符
- v-on -- 點擊事件
- v-model -- 雙向綁定
- 其他基礎知識速覽
- 快速使用
- 常識知識點
- key -- 作用 (后續要更新)
- computed -- 計算屬性
- watch -- 偵聽
- 防抖和節流
- vue3 -- 生命周期
- vue-cli 和 vite 項目搭建方法
- vite -- 導入動態圖片
- 組件
- 單文件組件 -- SFC
- 組件通信 -- porp
- 組件通信 -- $emit
- 組件通信 -- Provide / Inject
- 組件通信 -- 全局事件總線mitt庫
- 插槽 -- slot
- 整體使用案例
- 動態組件 -- is
- keep-alive
- 分包 -- 異步組價
- mixin -- 混入
- v-model-- 組件
- 使用計算屬性
- v-model -- 自定義修飾符
- Suspense -- 實驗屬性
- Teleport -- 指定掛載
- 組件實例 -- $ 屬性
- Option API VS Composition API
- Setup -- 組合API 入口
- api -- reactive
- api -- ref
- 使用ref 和 reactive 場景
- api -- toRefs 和 toRef
- api -- readonly
- 判斷性 -- API
- 功能性 -- API
- api -- computed
- api -- $ref 使用
- api -- 生命周期
- Provide 和 Inject
- watch
- watchEffect
- watch vs. watchEffect
- 簡單使用composition Api
- 響應性語法糖
- css -- 功能
- 修改css -- :deep() 和 var
- Vue3.2 -- 語法
- ts -- vscode 配置
- attrs/emit/props/expose/slots -- 使用
- props -- defineProps
- props -- defineProps Ts
- emit -- defineEmits
- emit -- defineEmits Ts
- $ref -- defineExpose
- slots/attrs -- useSlots() 和 useAttrs()
- 自定義指令
- Vue -- 插件
- Vue2.x 和 Vue3.x 不同點
- $children -- 移除
- v-for 和 ref
- attribute 強制行為
- 按鍵修飾符
- v-if 和 v-for 優先級
- 組件使用 v-model -- 非兼容
- 組件
- h -- 函數
- jsx -- 編寫
- Vue -- Router
- 了解路由和vue搭配
- vueRouter -- 簡單實現
- 安裝即使用
- 路由懶加載
- router-view
- router-link
- 路由匹配規則
- 404 頁面配置
- 路由嵌套
- 路由組件傳參
- 路由重定向和別名
- 路由跳轉方法
- 命名路由
- 命名視圖
- Composition API
- 路由守衛
- 路由元信息
- 路由其他方法 -- 添加/刪除/獲取
- 服務器配置映射
- 其他
- Vuex -- 狀態管理
- Option Api -- VUEX
- composition API -- VUEX
- module -- VUEX
- 刷新后vuex 數據同步
- 小技巧
- Pinia -- 狀態管理
- 開始使用
- pinia -- state
- pinia -- getter
- pinia -- action
- pinia -- 插件 ??
- Vue 源碼解讀
- 開發感悟
- 練手項目