Vue 中的 prop 屬性是父組件向子組件傳遞數(shù)據(jù)的一種方式。子組件通過聲明 props 來接收父組件傳遞的數(shù)據(jù)。這些數(shù)據(jù)可以在子組件的模板中被使用,也可以被用在計算屬性、方法或其他生命周期鉤子函數(shù)中。
下面是一個簡單的例子,展示如何在 Vue 中使用 props 屬性:
父組件:
```vue
<template>
<div>
<child-component :message="parentMessage"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
parentMessage: 'Hello from parent' // 這是我們將傳遞給子組件的數(shù)據(jù)
};
}
};
</script>
```
子組件(ChildComponent):
```vue
<template>
<div>
{{ message }} <!-- 這里顯示從父組件傳遞過來的數(shù)據(jù) -->
</div>
</template>
<script>
export default {
props: { // 在這里聲明我們將接收的 props 屬性
message: String // 我們期望從父組件接收一個字符串類型的消息(可以是任意類型)
}
};
</script>
```
在上面的例子中,父組件向子組件傳遞了一個名為 `message` 的 prop 屬性,子組件通過聲明 `props` 來接收這個屬性。當父組件的 `parentMessage` 數(shù)據(jù)改變時,子組件中的 `message` 也會相應(yīng)地更新。這就是 Vue 中 prop 的基本用法。你也可以為 prop 設(shè)置默認值、進行類型檢查、驗證等。