VUE.JS——元件基礎
阿新 • • 發佈:2019-01-01
vue.js 知識學完
元件可以擴充套件Html元素,封裝可重用的程式碼
元件也可以是原生的Html元素,以is特性擴充套件
1.建立元件:
var myComponent=Vue.extend({
template : '<div>component content</div>'
})
2.註冊元件:
Vue.component("tag-name",myComponent)
1和2 也可以直接寫成
Vue.component({
"tag-name":{"template":'<div>component content</div>'}
})
vue.js 背後會自動呼叫Vue.extend()
以上就註冊了一個自定義元素“tag-name”
3.元件的使用
建立vue例項
new vue({
el:"#example"
})
html程式碼使用
<div id="example">
<tag-name></tag-name>
</div>
其中自定義元素部分會替換為該元件對應的template內容
自定義元素的作用只是用作一個掛載點
4.區域性註冊:
可以讓元件只在其他元件內部使用
var child=Vue.extend({template:"<div></div>"})
var parent=Vue.extend({
template:“”,
components:{"child-tag":child }
})
只能在parent元件內使用child元件
5.模板解析
vue的模板為DOM模板。使用瀏覽器原生的解析器進行解析
6.Props 傳遞資料
可以使用props把資料傳遞給子元件
Vue.component("child",{
props:["myMessage"],
template:"<span>{{ myMessage }}</span>"
})
<child myMessage="hello"></child>
渲染為 :<span>hello</span>
7.props繫結型別
<child :msg=“parentMseg”></child> //預設單向
<child :msg.sync=“parentMseg”></child> //雙向繫結
<child :msg.once=“parentMseg”></child> //單次繫結
8.props可以指定驗證要求
Vue.component('example', {
props: {
// 基礎型別檢測 (`null` 意思是任何型別都可以)
propA: Number,
// 多種型別 (1.0.21+)
propM: [String, Number],
// 必需且是字串
propB: {
type: String,
required: true
},
// 數字,有預設值
propC: {
type: Number,
default: 100
}
}})
9.父子元件
this.$parent可以訪問子元件的父元件
this.$children 父元件的所有元素
10 .自定義事件
Vue實現了一個自定義事件介面,用於元件樹中通訊
每個vue例項都是一個事件觸發器
使用$on() 監聽事件
使用 $emit() 在他上面觸發事件
使用 $dispatch() 派發事件,事件沿著父鏈冒泡
使用 $broadcast() 廣播事件,事件向下傳導給所有的後代
11.slot 插槽 內容分發API
父元件的內容將被拋棄,除非子元件模板包含<slot>,如果子元件有一個slot,父元件的所有內容將查到slot所在地方 並替換
子元件(my-component )定義如下模板:
<div>
<h1>this is my component!</h1>
<slot></slot>
<slot name="one"></slot>
<slot name="two"></slot>
</div>
父元件模板:
<my-component>
<p>this some orignal content </p>
<p slot="one">this some more content 1 </p>
<p slot="two">this some more content 2</p>
</my-component>
最後的渲染結果:
<div>
<h1>this is my component!</h1>
<p>this some orignal content </p>
<p slot="one">this some more content 1 </p>
<p slot="two">this some more content 2</p>
</div>
12 .動態元件
多個元件可以使用同一個掛載點,然後動態的在他們之間切換。使用
保留的<component>元素,動態繫結到is特性
new Vue({
el : "body",
data:{
currentView:"home"
},
components:{
home:{/* */},
posts:{/* */},
archive:{/* */}
} })
keep-alive 可以把切換出去的元件保留在記憶體中,可保留狀態或避免重複渲染
<componet :is="currentView" keep-alive>
</componet>
13.兩個動態元件之間的過渡(transition-mode)
in-out :新元件先進入 過渡完成之後當前元件過度出去
out-in :當前元件過渡出去,過渡完成之後新元件過渡進入
<component :is="view" transition="fade" transition-mode="out-in">
</component>
css 樣式:
.fade-transition {
transition:opacity .3s ease;
}
.fade-enter , .fade-leave{
opcity:0;
}
14.元件和v-for
為了傳遞資料給元件,應當使用props
<my-component v-for="item in items" :item=item :index=$index>
</my-component>
15.可複用元件
可複用元件應當定義一個清晰的公開介面
vue.js元件API包含三部分: prop 事件 slot
prop :允許外部資料傳遞給元件
事件:允許元件觸發外部環境的action
slot:允許外部環境插內容到元件的檢視結構中去