vue通過props方式在子組件中獲取相應的對象(深拷貝)


這些方法主要是在這次做項目的過程中發現總結的來的,感覺也挺常用的,所以就簡單的記錄一下,希望下次不會再犯同樣的錯誤。

子組件定義props,父組件傳入數據,子組件在js中獲取的時候使用,如果是在html里面,可以直接把變量渲染上去。子組件獲取不到值時需要深拷貝

我就直接從代碼上面來進行

 

js代碼:

復制代碼
//子組件中,定義傳入的變量的類型等  
props: {
    data: {
      type: Array,
      require: true
    },
    status: {
      type: Boolean,
      require: false
    }
  }
復制代碼

我們可以直接在生命周期函數里面打印props

mounted(){
  let _this=this;
  console.log(_this._props,9999);          
}

 

方法一:

所以就可以直接拿取

mounted() {
     let _this=this;
     let {datas,status}=_this._props;
     console.log(datas,999999);
   },

 

方法二:

有時候會獲取不到,這時候可以用一個定時器來獲取

復制代碼
   mounted() {
     let _this=this;
     let {datas,status}=_this._props;
     setTimeout(()=>{
       console.log(this._props)
       console.log(datas,111111)
     },2000)
   }
復制代碼

 

方法三:

深拷貝

   mounted() {
     let _this=this;
      let props = {..._this._props};
      console.log(props,"props.......")
   },

 

方法四:

利用watch監聽

//直接監聽data,因為這里的props的變量名為data   
watch:{
     data(newData,prevData){
       console.log(newData,123654789)
     }
   }

 

沒錯啊,我的data就是一個數組。

 本文原作者路徑:https://www.cnblogs.com/epines/p/9518745.html

 


免責聲明!

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



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