Tùy chọn 'đạo cụ' của Vue
Ví dụ
Sử dụng tùy chọn props
để tạo props cho thành phần.
export default {
props: [
'foodName',
'foodDesc'
]
};
Chạy ví dụ »Xem thêm ví dụ bên dưới
Định nghĩa và cách sử dụng
Tùy chọn props
là một mảng (dạng đơn giản) hoặc một đối tượng (dạng đầy đủ), với tất cả các props bên trong.
Khi tùy chọn props
được đưa ra dưới dạng một mảng (dạng đơn giản, xem ví dụ ở trên), mảng đó chỉ bao gồm tên của các props dưới dạng chuỗi.
Khi tùy chọn props
được cung cấp dưới dạng đối tượng (dạng đầy đủ, xem ví dụ bên dưới), một số tùy chọn có thể được xác định ngoài tên prop:
Option | Description |
---|---|
type | Define the prop data type. Possible types: String, Number, Boolean, Array, Object, Date, Function, or Symbol. Vue will generate a warning if the actual provided prop is of a different type than what it is defined. |
default | Define a default prop value. If a specific prop is not provided by the parent component, the default value will be used. |
required | Define if a prop is required or not. When running the Vue application in development mode, Vue will generate a warning to the console in case a required prop is not provided. |
validator | Define a custom validator function. The function takes the prop value as an argument, and we can write out own rules for when a prop is valid or not. Returning false will generate a warning in development mode. |
Thêm ví dụ
Ví dụ
Xác định đạo cụ là đối tượng với các tùy chọn.
FoodItem.vue
:
<template>
<div>
<h2>{{ foodName }}</h2>
<p>{{ foodDesc }}</p>
</div>
</template>
<script>
export default {
props: {
foodName: {
type: String,
required: true
},
foodDesc: {
type: String,
required: false,
default: 'This is the food description...'
}
}
};
</script>
App.vue
:
<template>
<h1>Food</h1>
<p>Food description is not provided for 'Pizza' and 'Rice', so the default description is used.</p>
<div id="wrapper">
<food-item
food-name="Apples"
food-desc="Apples are a type of fruit that grow on trees."/>
<food-item
food-name="Pizza"/>
<food-item
food-name="Rice"/>
</div>
</template>
<style>
#wrapper {
display: flex;
flex-wrap: wrap;
}
#wrapper > div {
border: dashed black 1px;
flex-basis: 120px;
margin: 10px;
padding: 10px;
background-color: lightgreen;
}
</style>
Chạy ví dụ »Trang liên quan
Hướng dẫn Vue: Đạo cụ Vue
Hướng dẫn về Vue: Phương thức Vue $emit()
Tham khảo Vue: Đối tượng Vue $props