在vue2.0中父組件給子組件傳遞信息
父組件
import son from '../son/son.vue'
<template>
<div class="father">
<son :msg='msg'></son>
</div>
</template>
<script>
export default {
data() {
return {
'msg': '這是父組件的信息'
}
},
components: {
son
}
}
</script>
子組件
<template>
<div class="son">
<div>{{msg}}</div>
</div>
</template>
<script>
export default {
props: {//這里通過(guò)props接收父組件傳過(guò)來(lái)的信息腐螟,可以制定數(shù)據(jù)類型
msg: String
}
}
</script>
總結(jié)
- 父組件導(dǎo)入子組件
- 父組件中注冊(cè)子組件
- 把需要傳遞給子組件的值通過(guò)
v-bind
綁定在一個(gè)屬性上 - 子組件通過(guò)
props
接收父組件傳遞過(guò)來(lái)的信息
在vue2.0中子組件給父組件傳遞信息
子組件
<template>
<div class="son">
<div @click='sendToParent'>點(diǎn)擊發(fā)送數(shù)據(jù)</div>
</div>
</template>
<script>
export default {
methods:{
sendToParent() {
this.$emit('reciveMsg','這是傳遞給父組件的信息');
}
}
}
</script>
父組件
import son from '../son/son.vue'
<template>
<div class="father">
<son @reciveMsg='showMsg'></son>
</div>
</template>
<script>
export default {
methods:{
showMsg(data) {
console.log(data);//這里會(huì)輸出 `這是傳遞給父組件的信息`
}
},
components: {
son
}
}
</script>
總結(jié)
- 父組件導(dǎo)入子組件
- 父組件中注冊(cè)子組件
- 父組件綁定一個(gè)自定義的事件贤牛,子組件點(diǎn)擊的時(shí)候觸發(fā)這個(gè)事件
- 父組件給自定義事件綁定一個(gè)函數(shù),當(dāng)觸發(fā)這個(gè)自定義事件的時(shí)候健提,這個(gè)函數(shù)執(zhí)行扎狱,同時(shí)會(huì)接受一個(gè)參數(shù)侧到,這個(gè)參數(shù)就是從子組件傳遞過(guò)來(lái)的數(shù)據(jù)