100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > VUE父组件向子组件传递数据

VUE父组件向子组件传递数据

时间:2019-07-17 08:45:25

相关推荐

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">&#xe62d;</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

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。