前言
本文主要給大家介紹了關(guān)于vue中父組件通過props向子組件傳遞方法的相關(guān)內(nèi)容,分享出來供大家參考學(xué)習(xí),下面來一起看看詳細(xì)的介紹:
vue 組件中的 this
vue 中 data/computed/methods 中 this的上下文是vue實(shí)例,需注意。
例如:
注意:不應(yīng)該對(duì) data 屬性使用箭頭函數(shù) (例如data: () => { return { a: this.myProp }}
) 。理由是箭頭函數(shù)綁定了父級(jí)作用域的上下文,所以 this 將不會(huì)按照期望指向 Vue 實(shí)例,this.myProp
將是 undefined
https://cn.vuejs.org/v2/api/#methods
父組件通過props向子組件傳遞方法
父組件調(diào)用子組件,通過綁定callback屬性,將方法傳給子組件:
App.vue <search-bar class="f-fr" placeholder="請(qǐng)輸入名字" mutationName='resetListData' :callback="callback"/>
子組件通過props獲取父組件傳過來的callback方法:
SearchBar.vue export default { name: 'SearchBar', data() { return { input: '' } }, methods: { setName: function () { var input = this.input; if (input.trim() == '') { alert("empty"); } else { Api.searchTest(this.input,this.success ); } }, success(responseData) { this.callback(responseData); }, }, props: ['placeholder', 'apiName', 'moduleName', 'mutationName','callback'] }
通過 data
export default { ... data:function() { return { callback:function(responseData) { this.$store.commit('resetListData', responseData); } } }, ... };
此處callback以函數(shù)對(duì)象的方式,傳入子組件,子組件調(diào)用的時(shí)候,this指向子組件
通過 methods
export default { ... methods: { callback(responseData) { this.$store.commit('resetListData', responseData); } } };
此處callback是父組件的一個(gè)方法,個(gè)人理解,當(dāng)父組件初始化時(shí),該方法的this上下文就綁定了父組件的實(shí)例,因此當(dāng)子組件調(diào)用callback 方法時(shí),this指向父組件。
總結(jié)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com