Vue子組件向父組件傳值示范方法
一、要點概述
子組件:通過某種事件(這里是@click點擊事件,也可以是其他事件)發(fā)送數(shù)據(jù),this.$emit('事件名',要傳的數(shù)據(jù))
父組件:在標簽內(nèi)部@子組件中定義的事件名,等于一個函數(shù)(這里是rev),通過rev(val)這個函數(shù)接收數(shù)據(jù),把val賦值給自己的數(shù)據(jù)
二、分步講解
初始化Vue實例,可以理解為父組件,在父組件中的data中初始化一個變量(parentmsg),用來接收值;
let vm = new Vue({ el: '#app', data: { parentmsg:'' } });
自定義子組件,命名為Child,這個名字可以隨意起,template里直接給一個id名,可以直接在html中寫組件的內(nèi)容,不再需要使用模板字符串寫模板了,既方便又快捷;
在子組件的data函數(shù)里聲明一個變量(childmsg);
在子組件中寫一個點擊事件@click="send()",send函數(shù)內(nèi)部通過this.$emitthis.$emit('childsend',this.childmsg)向父組件發(fā)送數(shù)據(jù);this.$emit的第一個參數(shù)為事件名,自定義的,父組件需要通過這個事件名接收值;第二個參數(shù)為要傳給父組件的數(shù)據(jù);
Vue.component('Child',{ template:'#tp', data() { return { childmsg:'這是子組件中的數(shù)據(jù)' } }, methods: { send() { // 第一個參數(shù)為事件名,自定義的,父組件需要通過這個事件名接收值 // 第二個參數(shù)為要傳給父組件的數(shù)據(jù) this.$emit('childsend',this.childmsg) } } })
<!-- 子組件模板內(nèi)容 --> <template id="tp"> <div> <button @click="send">點我向父組件傳值</button> </div> </template>
在父組件中,通過@子組件中定義的事件名,觸發(fā)一個函數(shù)rev(val)來接收數(shù)據(jù),把接收到的val值賦給自己的變量parentmsg,然后就可以在html中使用插值表達式或v-bind綁定屬性值來使用子組件發(fā)送的數(shù)據(jù)了。
<div id="app"> <Child @childsend="rev"></Child> <h3>{{parentmsg}}</h3> </div> methods: { // 父組件接收數(shù)據(jù)的函數(shù) rev(val) { // val就是子組件發(fā)送的數(shù)據(jù) this.parentmsg = val } }
三、總代碼和運行結(jié)果
<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>子向父傳值</title> </head> <body> <!-- 父組件 @childsend="rev" --> <div id="app"> <Child @childsend="rev"></Child> <h3>{{parentmsg}}</h3> </div> <!-- 子組件 this.$emit('childsend',this.childmsg) --> <template id="tp"> <div> <button @click="send">點我向父組件傳值</button> </div> </template> <script src='https://cdn.jsdelivr.net/npm/vue/dist/vue.js'></script> <script> // 自定義子組件 Vue.component('Child',{ template:'#tp', data() { return { childmsg:'這是子組件中的數(shù)據(jù)' } }, methods: { send() { // 第一個參數(shù)為事件名,自定義的,父組件需要通過這個事件名接收值 // 第二個參數(shù)為要傳給父組件的數(shù)據(jù) this.$emit('childsend',this.childmsg) } } }) let vm = new Vue({ el: '#app', data: { parentmsg:'' }, methods: { // 父組件接收數(shù)據(jù)的函數(shù) rev(val) { // val就是子組件發(fā)送的數(shù)據(jù) this.parentmsg = val } } }); </script> </body> </html>
點擊之后父組件才能訪問子組件中的數(shù)據(jù)
到此這篇關(guān)于Vue子組件向父組件傳值示范方法的文章就介紹到這了,更多相關(guān)Vue子向父傳值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
如何實現(xiàn)echarts markline標簽名顯示自己想要的
這篇文章主要介紹了實現(xiàn)echarts markline標簽名顯示自己想要的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07詳解如何使用vue和electron開發(fā)一個桌面應(yīng)用
這篇文章主要為大家介紹了詳解如何使用vue和electron開發(fā)一個桌面應(yīng)用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03