Vue.js provide / inject 踩坑


最近學習JavaScript,並且使用vuejs,第一次使用依賴注入,結果踩坑,差點把屏幕摔了。。始終獲取不到如組件的屬性,provide中的this對象始終是子組件的this對象

慢慢也摸索到了些vuejs的一些門門道道。。。。

錯誤代碼1:this對象未定義錯誤

父組件
provide:{
            getCustomerId:this
        },


子組件
inject:['getCustomerId'],

子組件調用:
this.getCustomerId
//此時:getCustomerId 是未定義的

錯誤代碼2:this對象未定義錯誤

父組件
provide:{
        getCustomerId(){
            return this
            }
        },


子組件
inject:['getCustomerId'],

子組件調用:
this.getCustomerId
//此時:返回的this是子組件的this,此時注入的是getCustomerId這個方法,而這個方法並未在組件的methods中聲明

正確代碼:

父組件
provide(){
            return { getCustomerId: this.getCustomerId}
        },
 
         
   methods: {
            getCustomerId(){

            },
      }

子組件
inject:['getCustomerId'],

子組件調用:
this.getCustomerId
//此時:此時就對了,注入的是父組件methods中定義的getCustomerId方法,並且provide()改成的方法定義,執行此方法時,provide中的this對象也是父組件的this對象,

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM