前言
vue項(xiàng)目的一大亮點(diǎn)就是組件化。使用組件可以極大地提高項(xiàng)目中代碼的復(fù)用率,減少代碼量。但是使用組件最大的難點(diǎn)就是父子組件之間的通信。
子通信父
父組件
<template><div class="parent">我是父組件<!--父組件監(jiān)聽(tīng)子組件觸發(fā)的say方法,調(diào)用自己的parentSay方法--><!--通過(guò):msg將父組件的數(shù)據(jù)傳遞給子組件--><children :msg="msg" @say="parentSay"></children></div></template><script>import Children from './children.vue'export default {data () {return {msg: 'hello, children'}},methods: {// 參數(shù)就是子組件傳遞出來(lái)的數(shù)據(jù)parentSay(msg){console.log(msg) // hello, parent}},// 引入子組件components:{children: Children}}</script>子組件
<template><div class="hello"><div class="children" @click="say">我是子組件<div>父組件對(duì)我說(shuō):{{msg}}</div></div></div></template><script>export default {//父組件通過(guò)props屬性傳遞進(jìn)來(lái)的數(shù)據(jù)props: {msg: {type: String,default: () => {return ''}}},data () {return {childrenSay: 'hello, parent'}},methods: {// 子組件通過(guò)emit方法觸發(fā)父組件中定義好的函數(shù),從而將子組件中的數(shù)據(jù)傳遞給父組件say(){this.$emit('say' , this.childrenSay);}}}</script>子組件使用$emit方法調(diào)用父組件的方法,達(dá)到子通信父的目的。
父通信子
父組件
<!--Html--><template><!--父組件觸發(fā)click方法--><div class="parent" @click="say">我是父組件<!--通過(guò)ref標(biāo)記子組件--><children ref="child"></children></div></template><script>import Children from './children.vue'export default {data () {return {msg: "hello,my son"}},methods: {// 通過(guò)$refs調(diào)用子組件的parentSay方法say(){this.$refs.child.parentSay(this.msg);}},// 引入子組件components:{children: Children}}</script>子組件
<template><div class="hello"><div class="children" >我是子組件<div>父組件對(duì)我說(shuō):{{msg}}</div></div></div></template><script>export default {data () {return {msg: ''}},methods: {// 父組件調(diào)用的JavaScript方法parentSayparentSay(msg){this.msg = msg;}}}</script>父組件通過(guò) $refs 調(diào)用子組件的方法。
以上就是父子組件通信的方式,父子組件傳遞數(shù)據(jù)直接用props,或者使用 $emit 和 $refs 依靠事件來(lái)傳遞數(shù)據(jù)。
父子組件通信提升篇
上文中,子通信父是在 子中觸發(fā)點(diǎn)擊事件 然后調(diào)用父組件的方法,父通信子是在 父中觸發(fā)點(diǎn)擊事件 調(diào)用子組件的方法。但是實(shí)際情況中可能存在 子通信父時(shí)子組件不允許有點(diǎn)擊事件 而事件在父中或者 父通信子時(shí)點(diǎn)擊事件在子組件 中。
|
新聞熱點(diǎn)
疑難解答
圖片精選