您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)vue中怎么通過父組件點(diǎn)擊觸發(fā)子組件事件,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
父組件app.vue
<template> <div id="app"> <!--父組件--> <input v-model="msg"> <button v-on:click="notify">廣播事件</button> <!--子組件--> <popup ref="child" ></popup> </div> </template> <script> import popup from '@/components/popup' export default { name: 'app', data: function () { return { msg: '' } }, components: { popup }, methods: { notify: function () { if (this.msg.trim()) { this.$refs.child.parentMsg(this.msg) } } } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
子組件popup.vue
<template> <div> <ul> <li v-for="item in messages">父組件輸入了:{{item}}</li> </ul> </div> </template> <style> body { background-color: #ffffff; } </style> <script> export default{ name: 'popup', data: function () { return { messages: [] } }, methods: { parentMsg: function (msg) { this.messages.push(msg) } } } </script>
我把這個(gè)實(shí)例分為幾個(gè)步驟解讀:
1、父組件的button元素綁定click事件,該事件指向notify方法
2、給子組件注冊一個(gè)ref="child"
3、父組件的notify的方法在處理時(shí),使用了$refs.child把事件傳遞給子組件的parentMsg方法,同時(shí)攜帶著父組件中的參數(shù)msg
4、子組件接收到父組件的事件后,調(diào)用了parentMsg方法,把接收到的msg放到message數(shù)組中
運(yùn)行結(jié)果如下:
上述就是小編為大家分享的vue中怎么通過父組件點(diǎn)擊觸發(fā)子組件事件了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。