Vue之Props
1. Prop写法
在DOM模板中使用时,要使用横线分隔,如下的 post-title
Vue.component('blog-post', {// camelCase in Javascriptprops: ['postTitle'],template: '{{ postTitle }}
'
})
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
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 typespropB: [String, Number],// Required stringpropC: {type: String,required: true},// Number with a default valuepropD: {type: Number,default: 100},// Object with a default valuepropE: {type: Object,// Object or array defaults must be returned from// a factory functiondefault: function () {return { message: 'hello' }}},// Custom validator functionpropF: {validator: function (value) {// The value must match one of these stringsreturn ['success', 'warning', 'danger'].indexOf(value) !== -1}}}
})
6. 非Prop的Attribute
一个非 prop 的 attribute 是指传向一个组件,但是该组件并没有相应 prop 定义的 attribute。 而这些 attribute 会被添加到这个组件的根元素上。
例如:
// 在该组件的props中并未接受这个data-date-picker,然后这个 data-date-picker="activated" attribute 就会自动添加到 的根元素上。
(完)
更多Vue文档解读:《Vue Doc 笔记》