第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Vue組件內(nèi)的方法如何添加裝飾器Decorator

Vue組件內(nèi)的方法如何添加裝飾器Decorator

慕標(biāo)琳琳 2019-05-25 13:31:25
想要給Vue組件內(nèi)的某方法增加Decorator,發(fā)現(xiàn)并不能很好支持。importHellofrom'./components/Hello'importVuefrom'vue'importComponentfrom'vue-class-component'constlog=(target,name,descriptor)=>{constmethod=descriptor.valuedescriptor.value=(...args)=>{console.log(target,descriptor)method.apply(target,args)}returndescriptor}@Component({components:{Hello}})classAppextendsVue{str='Hello'@logfoo(){console.log(this.str)}}console.info('App',App)exportdefaultApp#app{font-family:'Avenir',Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-align:center;color:#2c3e50;margin-top:60px;}foo添加裝飾器log之后,this不能正確的指向Component本身。。
查看完整描述

2 回答

?
UYOU

TA貢獻(xiàn)1878條經(jīng)驗(yàn) 獲得超4個贊

問題在于log方法里面。
//descriptor.value=(...args)=>{
//console.log(target,descriptor)
//method.apply(target,args)
//}
//修改如下:
descriptor.value=function(...args){//這里不要用箭頭函數(shù),會在執(zhí)行環(huán)境中丟失正確的this指向
console.log(target,descriptor)
method.apply(this,args)//因?yàn)閐escriptor.value的運(yùn)行環(huán)境是在ClassApp中,所以這里的this會指向App。如果寫成箭頭那this就是log了
}
正常的Class在加裝飾器的時候使用method.apply(target,args)是沒有問題的。但是vue在注冊組件的時候會進(jìn)行初始化,this在這個時候被改變了(class內(nèi)部的的this變了,此時this!==target了
                            
查看完整回答
反對 回復(fù) 2019-05-25
?
白衣染霜花

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超10個贊

稍微改造一下就好了,針對vue實(shí)例做一下適配
constlog=(target,name,descriptor)=>{
constmethod=descriptor.value
descriptor.value=(...args)=>{
//判斷一下應(yīng)該使用的this指向
const_this=this.isVue?this:target;
console.log(target,descriptor)
method.apply(_this,args)
}
returndescriptor
}
                            
查看完整回答
反對 回復(fù) 2019-05-25
  • 2 回答
  • 0 關(guān)注
  • 685 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號