您好,登錄后才能下訂單哦!
在使用VUE開發(fā)的時候,有時候,我們需要通過父組件像子組件傳遞數(shù)據(jù)或者為了防止每個子組件都會有請求數(shù)據(jù)事件的發(fā)生,從而導(dǎo)致代碼冗余,所以,我們可以把同一個模塊下的所有子組件請求事件都放到父組件中去處理。
1、父組件通過屬性的方式給子組件傳值
//注意:":city"和":swiperList"這里定義的什么名字,子組件中props接收的就是什么名字
//? ? ?"city"和"swiper"是你data中定義的名字
<home-header :city='city'></home-header>
<home-swiper :swiperList='swiper'></home-swiper>
//js中
//data中定義好參數(shù)名,methods中獲取數(shù)據(jù)并賦值給data中的參數(shù)? ?
data(){
? ? return{
? ? ? ?city:'',
? ? ? ?swiper:[]
? ? }
},
methods:{
? ? getHomeInfo (){
? ? ? ? axios.get('/api/index.json')
? ? ? ? .then(this.getHomeInfoSuccess)
? ? },
? ? getHomeInfoSuccess(res){
? ? ? ? //這里面的數(shù)據(jù)獲取結(jié)構(gòu)取決于你自己的接口返回來的結(jié)構(gòu)
? ? ? ? res = res.data
? ? ? ? if(res.ret && res.data){
? ? ? ? ? ? const data = res.data
? ? ? ? ? ? this.city = data.city
? ? ? ? ? ? this.swiper = data.swiperList
? ? ? ? }
? ? }
},
2、子組件使用props接收父組件傳遞的屬性
子組件props中接收的參數(shù)只需要給其定義好數(shù)據(jù)類型即可!
Header子組件中:
<div class="header-right">
? ? {{ this.city }}
? ? <span class="iconfont arrow-icon"></span>
</div>
//js中
props:{
? ? city:String
}
Swiper子組件中:
<swiper :options="swiperOption">
? ? <swiper-slide v-for="item in swiperList" :key="item.id">
? ? ? ? <img class="swiper-img" :src="item.imgUrl" alt="">
? ? </swiper-slide>
? ? <div class="swiper-pagination"? slot="pagination"></div>
</swiper>
//js中
props:{
? ? swiperList: Array
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。