## 組件和組件間通信
### 組件
> 組件分為模版、腳本、樣式三個部分
> 我們新建一個名為son.vue的單文件組件
~~~html
<template>
<div>我是你的小兒子</div>
</template>
<script>
export default{
data(){
return {
hello:"bizzbee"
}
},
methods:{
}
}
</script>
<style>
</style>
~~~
> 我們在父組件中使用自組件
* 導入子組件
~~~
import son from './components/son'
~~~
* 注冊組件
~~~javascript
components: {
son
},
~~~
* 使用子組件
~~~javascript
<son />
~~~
### 組件間通信
> 組件間通信分為兩種:子組件->父組件、父組件->子組件

**父組件->子組件**
* 將需要傳遞給子組件的數據放到子組件標簽中
~~~html
<son name="今晚吃雞" />
~~~
* 父組件中用props接收,此時就可以直接在子組件中使用了
~~~javascript
export default{
props:['name'],
data(){
return {
hello:"bizzbee"
}
},
}
~~~
props屬性不僅可以接收數組,也可以接收對象。在接收對象是,可以指定接收值類型。
**動態傳遞**
* 使用v-bind綁定一個動態的值
~~~html
<input type="text" v-model="name" />
<son :name="name" />
~~~
**父組件<-子組件**
* 首先在子組件中定義一個事件,在事件的處理函數中調用`$emit()`方法
~~~html
<button @click="emitEvent">emit</button>
~~~
~~~javascript
methods:{
emitEvent(){
this.$emit('my-event',this.hello);
}
}
~~~
> $emit()方法的第一個參數是父組件中接收的時候需要用到的,第二個參數是向父組件傳遞的值。
* 在父組件的子組件標簽中定義一個$emit()觸發的事件,事件名是$emit()的第一個參數
~~~
<son :name="name" @my-event="getSon"/>
methods:{
getSon(name){
console.log(name);
}
}
~~~
**插槽功能**
>插槽功能是父組件向子組件傳遞一些類似模版的html片段。
* 在父組件的子組件標簽中,寫入一段html內容。
~~~html
<son :name="name" @my-event="getSon">
<h1>我是插槽里來得東西</h1>
</son>
~~~
* 在父組件中使用插槽傳遞的元素
~~~html
<slot></slot>
~~~
* 當我們需要細分插槽中的某些元素是,可以給插槽起個名字,也就是具名插槽
> 父組件
~~~html
<son :name="name" @my-event="getSon">
<h1>我是插槽里來得東西</h1>
<p slot="header">我是有名字的插槽</p>
</son>
~~~
> 子組件
~~~html
<slot name="header">no header</slot>
~~~
**動態組件**
用:is屬性將組件掛載到任意標簽上。
~~~
<p :is="currentComp"></p>
data(){
return {
currentComp:"son",
hello:"Hello,Bizzbee",
hi:"<p>hi,bizzbee</p>",
url:"http://cn.vuejs.org",
name:""
}
},
~~~