1.介紹
組件(Component)是 Vue.js 最強大的功能之一。
組件可以擴展 HTML 元素,封裝可重用的代碼。
註冊一個全局組件語法格式如下:Vue.component(tagName,options);tagName 爲組件名,options 爲配置選項
2.全局組件
2.1 html結構
texts 是自定義組件 ,message爲屬性名,該屬性名不可爲大寫,需要小寫。
<div id="app">
<texts class="text" message="自定義全局組件並通過props傳遞數據給子組件"></texts>
</div>
2.2 css樣式
<style>
*{
margin: 0;
padding: 0;
}
body{
font-family: Verdana,Arial,Helvetica,sans-serif;
font-size: 12px;
color: #222222;
}
#app{
text-align: center;
}
</style>
2.3 javascript邏輯
<script>
// 註冊組件 全局組件
Vue.component('texts', {
/**
* prop 是父組件用來傳遞數據的一個自定義屬性。
* 父組件的數據需要通過 props 把數據傳給子組件,子組件需要顯式地用 props 選項聲明 "prop"
*/
props:['message'],
template: '<h3>{{message}}</h3>'
})
// 創建根實例
new Vue({
el: '#app',
})
</script>
3.局部組件
3.1 html結構
<div id="app">
<images class="image"></images>
</div>
3.2 css樣式
*{ margin: 0; padding: 0; } body{ font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 12px; color: #222222; }
3.3 javascript邏輯
<script> //局部組件 var child = { template:'<img src="./src/assets/logo.png" alt="">' } // 創建根實例 new Vue({ el: '#app', components:{ //只能在父佈局中使用 'images':child, }, }) </script>
4.props 傳值
4.0 props動態傳值
prop 是父組件用來傳遞數據的一個自定義屬性。
父組件的數據需要通過 props 把數據傳給子組件,子組件需要顯式地用 props 選項聲明 "prop":
動態傳值,類似於用 v-bind 綁定 HTML 特性到一個表達式,也可以用 v-bind 動態綁定 props 的值到父組件的數據中。每當父組件的數據變化時,該變化也會傳導給子組件:4.1 html
<div id="app">
<input v-model="parentMessage">
<child v-bind:message="parentMessage"></child>
</div>
4.2 css
*{ margin: 0; padding: 0; } body{ font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 12px; color: #222222; } #app{ text-align: center; }
4.3 javascript
<script>
//動態props
Vue.component('child',{
props:['message'],
template:'<span>{{message}}</span>'
})
// 創建根實例
new Vue({
el: '#app',
data:{
parentMessage:'父組件內容',
},
})
</script>
5.自定義事件
5.0 介紹
父組件是使用 props 傳遞數據給子組件,但如果子組件要把數據傳遞回去,就需要使用自定義事件!
我們可以使用 v-on 綁定自定義事件, 每個 Vue 實例都實現了事件接口(Events interface),即:
- 使用
$on(eventName)
監聽事件 - 使用
$emit(eventName)
觸發事件
另外,父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。
5.1 html
<div id="app">
<p>{{total}}</p>
<buttons v-on:increment="incrementTotal"></buttons>
</div>
</div>
5.2 css
*{ margin: 0; padding: 0; } body{ font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 12px; color: #222222; } #app{ text-align: center; }
5.3 javascript
<script>
/**
* 自定義事件
* 父組件是使用 props 傳遞數據給子組件,但如果子組件要把數據傳遞回去,就需要使用自定義事件!
* 使用 v-on 綁定自定義事件, 每個 Vue 實例都實現了事件接口(Events interface),即:
* 使用 $on(eventName) 監聽事件
* 使用 $emit(eventName) 觸發事件
* 父組件可以在使用子組件的地方直接用 v-on 來監聽子組件觸發的事件。
*/
Vue.component('buttons',{
template: '<button v-on:click="increment">{{ counter }}</button>',
data:function () {
return {
counter:0,
}
},
methods:{
increment:function () {
this.counter += 1;
this.$emit('increment')
}
},
})
// 創建根實例
new Vue({
el: '#app',
data:{
total:0,
},
methods:{
incrementTotal:function () {
this.total += 1
}
}
})
</script>