Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 'props' 选项


示例

使用 props 选项为组件创建属性。

export default {
    props: [
        'foodName',
        'foodDesc'
    ]
};
运行示例 »

查看下方更多示例


定义和用法

The props 选项是一个数组(简单形式),或是一个对象(完整形式),包含所有属性。

props 选项作为数组给出时(简单形式,见上例),数组只包含属性名称作为字符串。

props 选项作为对象给出时(完整形式,见下例),除了属性名称之外,还可以定义几个选项

选项 描述
type 定义属性的数据类型。可能类型:String、Number、Boolean、Array、Object、Date、Function 或 Symbol。如果实际提供的属性类型与定义类型不同,Vue 会生成警告。
default 定义默认属性值。如果父组件没有提供特定属性,则将使用默认值。
required 定义属性是否为必需。当在开发模式下运行 Vue 应用程序时,如果未提供必需属性,Vue 会向控制台生成警告。
validator 定义自定义验证函数。该函数以属性值为参数,我们可以编写自己的规则来判断属性何时有效或无效。返回 false 会在开发模式下生成警告。

更多示例

示例

将属性定义为带有选项的对象。

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>
运行示例 »

相关页面

Vue 教程:Vue 属性

Vue 教程:Vue $emit() 方法

Vue 参考:Vue $props 对象


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.