Vue中父組件向子組件傳遞數(shù)據(jù)的幾種方法
最近在學(xué)習(xí)vue的源碼,總結(jié)了幾種vue中父子組件傳遞數(shù)據(jù)的方法。
1.props & event父組件向子組件傳遞props數(shù)據(jù),子組件通過觸發(fā)事件向父組件回傳數(shù)據(jù),代碼如下:
//子組件 <template> <div @click='changeName(’YYY’)'>{{name}}</div></template><script>export default{ props:[’name’],//or props:{name:{type:String,default:’’}} methods:{//不能在子組件修改props數(shù)據(jù),應(yīng)觸發(fā)事件讓父組件處理changeName(newName){ this.$emit(’changeName’,newName)} }}</script> //父組件<template> <div><child-comp :name='name' @changeName='changeName'></child-comp> </div></template><script> import childComp from ’path’ export default{data(){ return {name:’XXX’}},components:{ childComp},methods:{ changeName(newName){this.name = newName; }} }</scritp>
以上就是一個(gè)完整的流程,父組件通過props將數(shù)據(jù)傳遞給子組件,子組件則觸發(fā)事件,由父組件監(jiān)聽,并做相應(yīng)處理。
2.refref屬性可定義在子組件或原生DOM上,如果在子組件上,則指向子組件實(shí)例,如果在原生DOM上,則指向原生DOM元素(可以用做元素選擇,省去querySelector的煩惱)。
傳遞數(shù)據(jù)的思路:在父組件內(nèi)通過ref獲取子組件實(shí)例,然后調(diào)用子組件方法,并傳遞相關(guān)數(shù)據(jù)作為參數(shù)。代碼如下:
//子組件 <template> <div>{{parentMsg}}</div></template><script>export default{ data(){return { parentMsg:’’} }, methods:{getMsg(msg){ this.parentMsg = msg;} }}</script> //父組件<template> <div><child-comp ref='child'></child-comp><button @click='sendMsg'>SEND MESSAGE</button> </div></template><script> import childComp from ’path’ export default{components:{ childComp},methods:{ sendMsg(){this.$refs.child.getMsg(’Parent Message’); }} }</scritp>3.provide & inject 官方不推薦在生產(chǎn)環(huán)境使用
provide意為提供,當(dāng)一個(gè)組件通過provide提供了一個(gè)數(shù)據(jù),那么它的子孫組件就可以使用inject接受注入,從而可以使用祖先組件傳遞過來(lái)的數(shù)據(jù)。代碼如下:
//child<template> <div>{{appName}}</div></template><script>export default{ inject:[’appName’]}</script> // root export default{ data(){return { appName:’Test’} }, provide:[’appName’]}4.vuex
vue官方推薦的全局狀態(tài)管理插件。不細(xì)說。
到此這篇關(guān)于Vue中父組件向子組件傳遞數(shù)據(jù)的幾種方法的文章就介紹到這了,更多相關(guān)Vue 父組件向子組件傳遞數(shù)據(jù)內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 什么是Python變量作用域2. Android 實(shí)現(xiàn)徹底退出自己APP 并殺掉所有相關(guān)的進(jìn)程3. Vue實(shí)現(xiàn)仿iPhone懸浮球的示例代碼4. js select支持手動(dòng)輸入功能實(shí)現(xiàn)代碼5. Android studio 解決logcat無(wú)過濾工具欄的操作6. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式7. bootstrap select2 動(dòng)態(tài)從后臺(tái)Ajax動(dòng)態(tài)獲取數(shù)據(jù)的代碼8. 一個(gè) 2 年 Android 開發(fā)者的 18 條忠告9. PHP正則表達(dá)式函數(shù)preg_replace用法實(shí)例分析10. vue-drag-chart 拖動(dòng)/縮放圖表組件的實(shí)例代碼
