VUE父组件向子组件传递数据
?
在使用VUE開發的時候,有時候,我們需要通過父組件像子組件傳遞數據或者為了防止每個子組件都會有請求數據事件的發生,從而導致代碼冗余,所以,我們可以把同一個模塊下的所有子組件請求事件都放到父組件中去處理。
1、父組件通過屬性的方式給子組件傳值
//注意:":city"和":swiperList"這里定義的什么名字,子組件中props接收的就是什么名字
// "city"和"swiper"是你data中定義的名字
<home-header :city='city'></home-header>
<home-swiper :swiperList='swiper'></home-swiper>
//js中
//data中定義好參數名,methods中獲取數據并賦值給data中的參數
data(){
return{
city:'',
swiper:[]
}
},
methods:{
getHomeInfo (){
axios.get('/api/index.json')
.then(this.getHomeInfoSuccess)
},
getHomeInfoSuccess(res){
//這里面的數據獲取結構取決于你自己的接口返回來的結構
res = res.data
if(res.ret && res.data){
const data = res.data
this.city = data.city
this.swiper = data.swiperList
}
}
},
2、子組件使用props接收父組件傳遞的屬性
子組件props中接收的屬性參數只需要給其定義好數據類型,然后直接在模板中使用即可!
Header子組件中:
//template中
<div class="header-right">
{{ this.city }}
<span class="iconfont arrow-icon"></span>
</div>
//js中
props:{
city:String
}
Swiper子組件中:
//template中
<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
}
總結
以上是生活随笔為你收集整理的VUE父组件向子组件传递数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html字体怎么变大,网页字体怎么变大(
- 下一篇: html5 加速球 效果,css 渐隐渐