怎么在vue中實(shí)現(xiàn)組件傳值?針對這個(gè)問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡單易行的方法。
vue的組件傳值分為三種方式:父傳子、子傳父、非父子組件傳值
引用官網(wǎng)的一句話:父子組件的關(guān)系可以總結(jié)為 prop 向下傳遞,事件向上傳遞
父組件通過 prop 給子組件下發(fā)數(shù)據(jù),子組件通過事件給父組件發(fā)送消息,如下圖所示:
下面我們就開始用代碼(一言不合就上代碼)詳細(xì)的介紹vue組件傳值的三種方式
1、父傳子子組件的代碼:
<template> <div id="container"> {{msg}} </div> </template> <script> export default { data() { return {}; }, props:{ msg: String } }; </script> <style scoped> #container{ color: red; margin-top: 50px; } </style>
父組件的代碼:
<template> <div id="container"> <input type="text" v-model="text" @change="dataChange"> <Child :msg="text"></Child> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { text: "父組件的值" }; }, methods: { dataChange(data){ this.msg = data } }, components: { Child } }; </script> <style scoped> </style>
父傳子的實(shí)現(xiàn)方式就是通過props屬性,子組件通過props屬性接收從父組件傳過來的值,而父組件傳值的時(shí)候使用 v-bind 將子組件中預(yù)留的變量名綁定為data里面的數(shù)據(jù)即可
2、子傳父子組件代碼:
<template> <div id="container"> <input type="text" v-model="msg"> <button @click="setData">傳遞到父組件</button> </div> </template> <script> export default { data() { return { msg: "傳遞給父組件的值" }; }, methods: { setData() { this.$emit("getData", this.msg); } } }; </script> <style scoped> #container { color: red; margin-top: 50px; } </style>
父組件代碼:
<template> <div id="container"> <Child @getData="getData"></Child> <p>{{msg}}</p> </div> </template> <script> import Child from "@/components/Child"; export default { data() { return { msg: "父組件默認(rèn)值" }; }, methods: { getData(data) { this.msg = data; } }, components: { Child } }; </script> <style scoped> </style>
子傳父的實(shí)現(xiàn)方式就是用了 this.$emit 來遍歷 getData 事件,首先用按鈕來觸發(fā) setData 事件,在 setData 中 用 this.$emit 來遍歷 getData 事件,最后返回 this.msg
總結(jié):
子組件中需要以某種方式例如點(diǎn)擊事件的方法來觸發(fā)一個(gè)自定義事件
將需要傳的值作為$emit的第二個(gè)參數(shù),該值將作為實(shí)參傳給響應(yīng)自定義事件的方法
在父組件中注冊子組件并在子組件標(biāo)簽上綁定對自定義事件的監(jiān)聽
關(guān)于怎么在vue中實(shí)現(xiàn)組件傳值問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。
文章題目:怎么在vue中實(shí)現(xiàn)組件傳值-創(chuàng)新互聯(lián)
當(dāng)前網(wǎng)址:http://chinadenli.net/article10/dgpddo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、網(wǎng)站設(shè)計(jì)公司、建站公司、網(wǎng)站收錄、搜索引擎優(yōu)化、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容