詳解vue中在父組件點(diǎn)擊按鈕觸發(fā)子組件的事件
我把這個(gè)實(shí)例分為幾個(gè)步驟解讀:
1、父組件的button元素綁定click事件,該事件指向notify方法2、給子組件注冊(cè)一個(gè)ref=“child”3、父組件的notify的方法在處理時(shí),使用了$refs.child把事件傳遞給子組件的parentMsg方法,同時(shí)攜帶著父組件中的參數(shù)msg 4、子組件接收到父組件的事件后,調(diào)用了parentMsg方法,把接收到的msg放到message數(shù)組中
父組件
<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>
子組件
<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>
到此這篇關(guān)于詳解vue中在父組件點(diǎn)擊按鈕觸發(fā)子組件的事件的文章就介紹到這了,更多相關(guān)vue 父組件觸發(fā)子組件內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用EF Code First搭建簡(jiǎn)易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫(kù)遷移2. intellij idea寫(xiě)Python教程3. ThinkPHP6使用JWT+中間件實(shí)現(xiàn)Token驗(yàn)證實(shí)例詳解4. 利用VS2019創(chuàng)建Web項(xiàng)目并發(fā)送到IIS及IIS與ASP.NET配置教程5. Python 用NumPy創(chuàng)建二維數(shù)組的案例6. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲7. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法8. jsp filter 過(guò)濾器功能與簡(jiǎn)單用法示例9. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?10. 使用HttpClient消費(fèi)ASP.NET Web API服務(wù)案例
