Vue之Props
1. Prop写法
在DOM模板中使用时,要使用横线分隔,如下的 post-title
Vue.component('blog-post', {
// camelCase in JavaScript
props: ['postTitle'],
template: '<h3>{{ postTitle }}</h3>'
})
<!-- kebab-case in HTML -->
<blog-post post-title="hello!"></blog-post>
2. 规定Prop数据类型
props
的两种写法,后一种写法,可以规定数据的类型,不符合类型,vue会抛出警告
// 写法一
props: ['title', 'likes', 'isPublished', 'commentIds', 'author']
// 写法二
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise // or any other constructor
}
3. 传递静态或动态Props
除了string,还可传递任意类型的prop数据:number、boolean、array、object
// 静态的
<blog-post title="My journey with Vue"></blog-post>
// 动态的
<!-- Dynamically assign the value of a variable -->
<blog-post v-bind:title="post.title"></blog-post>
4. 单向数据流
父组件通过props
向子组件传递数据,影响子组件状态
5. 对Prop进行类型检查
示例:
Vue.component('my-component', {
props: {
// Basic type check (`null` and `undefined` values will pass any type validation)
propA: Number,
// Multiple possible types
propB: [String, Number],
// Required string
propC: {
type: String,
required: true
},
// Number with a default value
propD: {
type: Number,
default: 100
},
// Object with a default value
propE: {
type: Object,
// Object or array defaults must be returned from
// a factory function
default: function () {
return { message: 'hello' }
}
},
// Custom validator function
propF: {
validator: function (value) {
// The value must match one of these strings
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
6. 非Prop的Attribute
一个非 prop 的 attribute 是指传向一个组件,但是该组件并没有相应 prop 定义的 attribute。 而这些 attribute 会被添加到这个组件的根元素上。
例如:
<bootstrap-date-input data-date-picker="activated"></bootstrap-date-input>
// 在该组件的props中并未接受这个data-date-picker,然后这个 data-date-picker="activated" attribute 就会自动添加到 <bootstrap-date-input> 的根元素上。
(完)
更多Vue文档解读:《Vue Doc 笔记》