Vue.js 组件
组件(Component)可以扩展 HTML 元素,封装可重用的代码。
注册一个组件的语法:
Vue.component(tagName,options)
tagname为组件名,options为配置项。注册后调用组件的方式:
<tagName></tagName>
- 全局组件
<div id="div">
<hello></hello>
</div>
<script>
Vue.component.('hello',{
template:'<h1>自定义hello组件</h1>'
});
new Vue({
el:'div'
});
</script>
- 局部组件
<div id="div">
<hello></hello>
</div>
<script>
var hello = {
template:'<h1>自定义hello组件</h1>'
}
new Vue({
el:'div',
components:{
'hello': hello
}
});
</script>
- Prop
prop 是父组件用来传递数据的自定义属性。
<div id="div">
<hello str="hello"></hello>
</div>
<script type="text/javascript">
Vue.component('hello',{
props:['str'],
template : '<h1>{{ str }}</h1>'
});
new Vue({
el : '#div'
})
</script>
- 动态Prop
使用 v-bind 动态绑定 props 的值到父组件的数据中,每当父组件的值发生改变时,也会传导给子组件。
<div id="div">
<input type="text" v-model="parentStr">
<hello v-bind:str="parentStr"></hello>
</div>
<script type="text/javascript">
Vue.component('hello',{
props:['str'],
template : '<h1>{{ str }}</h1>'
});
new Vue({
el : '#div',
data : {
parentStr : '父组件内容'
}
})
</script>
- prop验证
组件可以为 props 指定验证要求。
<script type="text/javascript">
Vue.component('hello', {
props: {
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
base: Number,
// 多个可能的类型
strnum: [String, Number],
// 必填的字符串
allowBlank: {
type: String,
required: true
},
// 带有默认值的数字
num: {
type: Number,
default: 100
},
// 带有默认值的对象
obj: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
customize: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
//
}
}
}
})
</script>
当 prop 验证失败的时候,将会产生一个控制台的警告,type 可以是下面原生构造器:
String
Number
Boolean Array Object Date Function Symbol