關(guān)鍵詞:prop
漸進(jìn)式探索學(xué)習(xí)(官網(wǎng)的例子)
<div id="demo">
<child message="hello!"></child>
</div>
Vue.component('child', {
// 聲明 props
props: ['message'],
// 就像 data 一樣,prop 可以用在模板內(nèi)
// 同樣也可以在 vm 實(shí)例中像 “this.message” 這樣使用
template: '<span>{{ message }}</span>'
})
var vm = new Vue({
el: "#demo"
})
來個(gè)復(fù)雜點(diǎn)的,實(shí)現(xiàn)父組件向子組件傳數(shù)據(jù)
Vue.component('child', {
props: ['message'],
template: `
<div>
<h3>{{title}}</h3>
<p>{{ message }}</p>
</div>
`,
data(){
return { title: '越人歌' } // 注意寫成函數(shù)形式
}
})
var vm = new Vue({
el: "#demo",
data:{
poem:['山有木兮木有枝','心悅君兮君不知']
}
})
傳兩個(gè)數(shù)據(jù)試試
Vue.component('child', {
props: ['message','time'],
template: `
<div>
<h3>{{title}}</h3>
<p>{{ message }}</p>
<i>{{time}}</i>
</div>
`,
data(){
return { title: '越人歌' }
}
})
var vm = new Vue({
el: "#demo",
data:{
poem:['山有木兮木有枝','心悅君兮君不知'],
age:'3000年'
}
})
<div id="demo">
<child v-for= "item1 in poem":message="item1" :time="age"></child>
</div>
Prop 驗(yàn)證
組件可以為 props 指定驗(yàn)證要求。如果未指定驗(yàn)證要求,Vue 會(huì)發(fā)出警告。當(dāng)組件給其他人使用時(shí)這很有用。
prop 是一個(gè)對(duì)象而不是字符串?dāng)?shù)組時(shí),它包含驗(yàn)證要求:
Vue.component('example', {
props: {
// 基礎(chǔ)類型檢測(cè) (`null` 意思是任何類型都可以)
propA: Number,
// 多種類型
propB: [String, Number],
// 必傳且是字符串
propC: {
type: String,
required: true
},
// 數(shù)字,有默認(rèn)值
propD: {
type: Number,
default: 100
},
// 數(shù)組/對(duì)象的默認(rèn)值應(yīng)當(dāng)由一個(gè)工廠函數(shù)返回
propE: {
type: Object,
default: function () {
return { message: 'hello' }
}
},
// 自定義驗(yàn)證函數(shù)
propF: {
validator: function (value) {
return value > 10
}
}
}
})
這時(shí)候我們?cè)賮砀膶懸幌?/p>
Vue.component('child', {
props: {
'time': {
type: Number,
default: 1000
},
'message' :{
type: Object,
default: function () {
return { message: 'hello' }
}
}
},
template: `
<div>
<h3>{{title}}</h3>
<p>{{ message }}</p>
<i>{{time}}</i>
</div>
`,
data(){
return { title: '越人歌' }
}
})
var vm = new Vue({
el: "#demo",
data:{
poem:['山有木兮木有枝','心悅君兮君不知'],
/*age:3000*/
}
})
<div id="demo">
<child v-for= "item1 in poem":message="item1"></child>
</div>