本文共 2678 字,大约阅读时间需要 8 分钟。
组件用.vue还是.js
Props are the way components can accept data from components that include them (parent components).
道具是组件可以从包含它们的组件(父组件)接受数据的方式。
When a component expects one or more prop, it must define them in its props
property:
当组件需要一个或多个道具时,必须在其props
属性中定义它们:
Vue.component('user-name', { props: ['name'], template: 'Hi {
{ name }}'})
or, in a Vue Single File Component:
或者,在Vue单个文件组件中:
{
{ name }}
You can have multiple props by appending them to the array:
您可以通过将多个道具附加到数组来拥有多个道具:
Vue.component('user-name', { props: ['firstName', 'lastName'], template: 'Hi {
{ firstName }} { { lastName }}'})
You can specify the type of a prop by using an object instead of an array, using the name of the property as the key of each property, and the type as the value:
您可以通过使用对象而不是数组,将属性名称用作每个属性的键,并将类型用作值来指定道具的类型:
Vue.component('user-name', { props: { firstName: String, lastName: String }, template: 'Hi {
{ firstName }} { { lastName }}'})
The valid types you can use are:
您可以使用的有效类型是:
When a type mismatches, Vue alerts (in development mode) in the console with a warning.
当类型不匹配时,Vue在控制台中以警告方式警告(处于开发模式)。
Prop types can be more articulated.
道具类型可以更清晰地表达。
You can allow multiple different value types:
您可以允许多种不同的值类型:
props: { firstName: [String, Number]}
You can require a prop to be mandatory:
您可以要求道具是强制性的:
props: { firstName: { type: String, required: true }}
You can specify a default value:
您可以指定一个默认值:
props: { firstName: { type: String, default: 'Unknown person' }}
For objects:
对于对象:
props: { name: { type: Object, default: { firstName: 'Unknown', lastName: '' } }}
default
can also be a function that returns an appropriate value, rather than being the actual value.
default
也可以是返回适当值的函数,而不是实际值。
You can even build a custom validator, which is cool for complex data:
您甚至可以构建一个自定义验证器,该验证器对复杂数据很酷:
props: { name: { validator: name => { return name === 'Flavio' //only allow "Flavios" } }}
You pass a prop to a component using the syntax
您使用语法将prop传递给组件
if what you pass is a static value.
如果您传递的是静态值。
If it’s a data property, you use
如果它是数据属性,则使用
You can use a ternary operator inside the prop value to check a truthy condition and pass a value that depends on it:
您可以在prop值内使用三元运算符来检查真实条件并传递依赖于该条件的值:
翻译自:
组件用.vue还是.js
转载地址:http://utqgb.baihongyu.com/