一、camelCased(駝峰式命名)與 kebab--case(短橫線命名)
- 在 html 中渲染組件時不可以使用 camelCased(駝峰式命名)。因為在 html 中
myComponent和mycomponent是一致的(除非被雙引號包裹),所以在組件的 html 中必須使用 kebab--case(短橫線命名)。 - 在組件中,父組件給子組件傳遞數(shù)據(jù)必須用短橫線命名。
- 在組件的
template中,必須使用駝峰式命名;若為短橫線命名方式,則會直接報錯。 - 在組件的
data中,用this.xxx引用時,只能使用駝峰式命名;若為短橫線的命名方式,則會報錯。
二、數(shù)據(jù)驗證
數(shù)據(jù)驗證主要是對 props 傳遞進來的數(shù)據(jù)進行類型的驗證,并可以對其設定一個選項,如設置默認值或特定的數(shù)據(jù)類型。
可驗證的 type 類型包括:
- String
- Number
- Boolean
- Object
- Array
- Function
數(shù)據(jù)驗證示例:
<div id="app">
<type-component :a="a" :b="b" :c="c" :d="d" :f="f" :g="g"></type-component>
</div>
<script>
var app = new Vue({
el: "#app",
data: {
a: '1',
b: '666',
c: true,
d: 12345,
e: [],
f: 88,
g: console.log()
},
components: {
'type-component': {
props: {
// 必須是數(shù)字類型
a: String,
// 必須是字符串或數(shù)字類型
b: [String,Number],
// 布爾類型,如果沒有定義,默認值就是true
// 參數(shù):type 類型,required 是否必傳,default 默認值
c: {
type: Boolean,
default: true
},
// 數(shù)字類型,而且d在頁面中必傳,不傳則報錯
d: {
type: Number,
required: true
},
// 數(shù)組或?qū)ο?,默認值必須用函數(shù)來返回(頁面不綁定e時取默認值)
e: {
type: Array,
default: function(){
return [666]
}
},
// 自定義一個驗證函數(shù)
f: {
validator: function(value){
return value>10
}
},
// g必須傳函數(shù),否則報錯
g: {
type: Function
}
},
template: '<div>{{a}}--{}--{{c}}--{u0z1t8os}--{{e[0]}}</div>'
}
}
})
</script>