vue通過props方式在子組件中獲取相應(yīng)的對象

同人博客搬遷~~~~(播客主頁:https://www.cnblogs.com/epines/

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

子組件定義props,父組件傳入數(shù)據(jù),子組件在js中獲取的時(shí)候使用,如果是在html里面,可以直接把變量渲染上去。

我就直接從代碼上面來進(jìn)行


js代碼:

//子組件中,定義傳入的變量的類型等? props: {

? ? data: {

? ? ? type: Array,

? ? ? require: true? ? },

? ? status: {

? ? ? type: Boolean,

? ? ? require: false? ? }

? }

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

mounted(){

? let _this=this;

? console.log(_this._props,9999);? ? ? ? ?

}


方法一:

所以就可以直接拿取

mounted() {

? ? let _this=this;

? ? let {datas,status}=_this._props;

? ? console.log(datas,999999);

? },


方法二:

有時(shí)候會獲取不到,這時(shí)候可以用一個(gè)定時(shí)器來獲取

? 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監(jiān)聽

//直接監(jiān)聽data,因?yàn)檫@里的props的變量名為data? watch:{

? ? data(newData,prevData){

? ? ? console.log(newData,123654789)

? ? }

? }


沒錯(cuò)啊,我的data就是一個(gè)數(shù)組。


在這四種方法的逐級使用下,終于獲取到了我想要的data。

其實(shí)其他幾種都是可以的,只是不知道為什么在這次項(xiàng)目中的某個(gè)地方,前面幾種都失效了,(其他地方是成功的),可能是因?yàn)槲矣卸景?╭(╯ε╰)╮。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容