前面分了五个章节讲了Vue的基础内容,从最简单的定义,到组件基础。有了这5个章节,让我们对vue有了基本的了解,有了这些基础也可以开发简单的应用了,以为接下的深入学习打下了基础。
一、组件注册
定义的组件名字必须为字母全小写且必须包含一个连字符。这会帮助你避免和当前以及未来的 HTML 元素相冲突。
<my-component-name>
和 <MyComponentName>
都是可接受的。注意,尽管如此,直接在 DOM (即非字符串的模板) 中使用时只有 kebab-case 是有效的。
组件全局注册方式:
1 app.component('component-a', { 2 /* ... */ 3 })
局部注册方式就是我们在基础章节时使用的示例就是局步注册的。
二、Prop
每个 prop 都可以是指定的值类型。这时,可以以对象形式列出 prop,这些 property 的名称和值分别是 prop 各自的名称和类型:
1 props: { 2 title: String, 3 likes: Number, 4 isPublished: Boolean, 5 commentIds: Array, 6 author: Object, 7 callback: Function, 8 contactsPromise: Promise // 或任何其他构造函数 9 }
数据的传递也就是属性的赋值,这个就比较简单了不再列出示例。下面来看一下数据类型的验证:
1 props: { 2 // Basic type check (`null` and `undefined` values will pass any type validation) 3 propA: Number, 4 // Multiple possible types 5 propB: [String, Number], 6 // Required string 7 propC: { 8 type: String, 9 required: true 10 }, 11 // Number with a default value 12 propD: { 13 type: Number, 14 default: 100 15 }, 16 // Object with a default value 17 propE: { 18 type: Object, 19 // Object or array defaults must be returned from 20 // a factory function 21 default: function() { 22 return { message: 'hello' } 23 } 24 }, 25 // Custom validator function 26 propF: { 27 validator: function(value) { 28 // The value must match one of these strings 29 return ['success', 'warning', 'danger'].indexOf(value) !== -1 30 } 31 }, 32 // Function with a default value 33 propG: { 34 type: Function, 35 // Unlike object or array default, this is not a factory function - this is a function to serve as a default value 36 default: function() { 37 return 'Default function' 38 } 39 } 40 }
这个也没什么好解释的,一看就懂。
三、非 Prop 的 Attribute
一个非 prop 的 attribute 是指传向一个组件,但是该组件并没有相应 props 或 emits 定义的 attribute。常见的示例包括 class
、style
和 id
属性。
当组件返回单个根节点时,非 prop attribute 将自动添加到根节点的 attribute 中。如果不希望组件的根元素继承 attribute,可以在组件的选项中设置 inheritAttrs: false
。
1 { 2 inheritAttrs: false, 3 template: ` 4 <div class="date-picker"> 5 <input type="datetime" v-bind="$attrs" /> 6 </div> 7 ` 8 }