子組件嵌套在父組件內部,父組件給子組件傳遞一個標識,在子組件內部用props接收,子組件在模板裏能夠經過{{}}的形式進行使用。若是父組件給子組件傳遞的標識中含有—,子組件在接收時採用駝峯式接收。vue
2 子組件給父組件傳值數組
<template id="son">
<div>
我是孩子
<button @click="giveMoney(10000)">給父母打錢</button>
</div>
</template>
<template id="test">
<div>
<button @click='count++'>點擊次數{{count}}</button>,
這個月孩子打了{{money}}元錢
<v-son @to-parent="getMoney"></v-son>
</div>
</template>this
const Son = {
template: "#son",
data () {
return {
}
},
methods: {
giveMoney (val) {
// 你辦了卡,把卡給了父母,你打錢
this.$emit('to-parent', val)
}
}
}
// 一、定義組件 ---- 組件的首字母必須大寫
const Test = {
template: "#test",
data () {
return {
money: 0
}
},
methods:{
getMoney ( val ) {
this.money = val
}
},
components: {
'v-son': Son
}
}prototype
非父子間的傳值我我的以爲算是組件傳值中最麻煩的一個,你說它難她也難,說它簡單它也簡單,咱們只要定義好一方負責監聽一方負責觸發便可,他們之間相互傳值依據的是中央事件總線,也就是new vue ,至關於飛機場中的塔臺同樣,都受它指揮。code
$on 負責監聽事件 $emit 負責觸發事件 並傳遞參數 若是有AB兩個組件,若是A要給B傳值,B就必須先監聽A,使用起來比較麻煩。 事件的中央總線 (飛機塔臺,郵差的故事) 在src下建立bus.js var bus = new Vue() //中央事件總線 export default bus ; 假若有AB兩個組件 在AB組件中引入bus中央事件總線
在A組件中發送一個信息給B組件component
methods:{ sendData(val){ bus.$emit("A-B",val) } } mounted(){ bus.$on("B-A",function(val){ console.log(val) }) } 在B組件內接收 mounted(){ bus.$on("A-B",function(val){ console.log(val) bus.$emit("B-A",val) }) }
若是AB組件有兩次交互,就會有四次事件,若是作三次事件就會有六次事件
其實最麻煩的不是他們之間的傳值,而是定義他們之間的事件名稱,若是沒有一套完備定義事件名稱的規則,會無故的增長項目開發的週期,下降了開發效率,代碼的耦合度會增長,維護性也低了。
因此不建議使用事件
能夠在main.js中 vue.prototype.$bus = new Vue()在原型上擴展一個$bus 不用單建立bus文件 經過this.$bus.$on()進行使用