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>
以上就是一個完整的流程,父組件通過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)一個組件通過provide提供了一個數(shù)據(jù),那么它的子孫組件就可以使用inject接受注入,從而可以使用祖先組件傳遞過來的數(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)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用Python和百度語音識別生成視頻字幕的實(shí)現(xiàn)2. css代碼優(yōu)化的12個技巧3. CSS可以做的幾個令你嘆為觀止的實(shí)例分享4. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法5. 利用ajax+php實(shí)現(xiàn)商品價(jià)格計(jì)算6. xml中的空格之完全解說7. Vue的Options用法說明8. axios和ajax的區(qū)別點(diǎn)總結(jié)9. 怎樣才能用js生成xmldom對象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?10. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)
