Vue組件基礎(chǔ)
每用一次組件,就會(huì)有一個(gè)它的新實(shí)例被創(chuàng)建
data必須是一個(gè)函數(shù)
一個(gè)組件的data選項(xiàng)必須是一個(gè)函數(shù),因此每個(gè)函數(shù)可以維護(hù)一份被返回對(duì)象的獨(dú)立拷貝。
避免一個(gè)實(shí)例,影響到其他所有實(shí)例。
動(dòng)態(tài)傳遞prop
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:title="post.title"
></blog-post>
可以使用v-bind來(lái)動(dòng)態(tài)傳遞prop。一開始不清楚要渲染的具體內(nèi)容,比如從一個(gè)api獲取博文列表的時(shí)候,是非常有用的。
單個(gè)根元素
每個(gè)組件必須只有一個(gè)根元素
當(dāng)組件變得越來(lái)越復(fù)雜的時(shí)候,為每個(gè)相關(guān)信息定義一個(gè)prop會(huì)變得很麻煩。
所以讓它變成一個(gè)單獨(dú)的post prop
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post>
<script>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
`
})
</script>
在組件上使用v-model
自定義事件也可以用于創(chuàng)建v-model的自定義組件
v-mdoel實(shí)際上為語(yǔ)法糖
<input v-model="searchText">
//等價(jià)于
<input
v-bind:value="searchText"
v-on:input="searchText = $event.target.value"
>
當(dāng)用在組件上時(shí),v-model則會(huì)這樣
<custom-input
v-bind:value="searchText"
v-on:input="searchText = $event"
></custom-input>
為了讓它正常工作,這個(gè)組件內(nèi)的<input>
- 將其value特性綁定到一個(gè)名叫value的prop上
- 在其input事件被觸發(fā)時(shí),將新的值通過(guò)自定義的input事件拋出
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)"
>
`
})
//重寫input事件傳出的值,因?yàn)関-model在自定義組件和在<input>上不一致
通過(guò)插槽分發(fā)內(nèi)容
在需要的地方加入插槽
動(dòng)態(tài)組件
<!-- 組件會(huì)在 `currentTabComponent` 改變時(shí)改變 -->
<component v-bind:is="currentTabComponent"></component>
動(dòng)態(tài)和異步組件
解析DOM模版時(shí)的注意事項(xiàng)
有些 HTML 元素,諸如<ul>,<ol>,<table><select>,對(duì)于哪些元素可以出現(xiàn)在其內(nèi)部是有嚴(yán)格限制的。而有些元素,諸如 <li>,<tr>,<option>,只能出現(xiàn)在其它某些特定的元素內(nèi)部
使用這些有約束條件的元素時(shí)會(huì)遇到一些問(wèn)題
<table>
<blog-post-row></blog-post-row>
</table>
這個(gè)自定義組件<blog-post-row> 會(huì)被作為無(wú)效的內(nèi)容提升到外部,并導(dǎo)致最終渲染結(jié)果出錯(cuò)。幸好這個(gè)特殊的 is 特性給了我們一個(gè)變通的辦法:
<table>
<tr is="blog-post-row"></tr>
</table>
需要注意的是以下來(lái)源使用模版的話,這條限制是不存在的
- 字符串 (例如:
template: '...') - 單文件組件 (
.vue) <script type="text/x-template"></script>