微信小程序从服务器加载数据并传入自定义组件

1.尝试访问服务端数据

在onLoad函数下添加

wx.request({
	url: 'http://... '
})

比想象的简单很多有没有

接下来在控制台打印一下,看看服务器返回的数据的详情。

wx.request({
	url: 'http://... '
	suceess(res){
		console.log(res)
	}
})

res参数这个参数请不要慌张,就是由服务器传回来的所有的数据
在这里插入图片描述

2.页面数据绑定

接下来需要进行数据绑定,这里可能会出现this指代不明的情况,原因是上面又有一层succes函数。
对应的解决方法是使用箭头函数,箭头函数会使函数体里的this为箭头函数上一层函数的this,即 箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this Mdn_arrowfunc

  wx.request({
      url: app.gBaseUrl + 'in_theaters?start=0&count=3',
      success:(res)=>{
        console.log(res)
        this.setData({
          inTheaters:res.data.subjects
        })
      }

    })

在data下

  data: {
    inTheaters:[] 
  },

这一步只是绑定到页面上,最终需要把数据传入组件进行显示,所以需要进一步数据绑定。
这个页面的组件有movie-list和内嵌于他的movie,需要把数据传进去。

3.数据绑定组件成功显示

步骤1:在js文件下先自定义属性
在components/movie-list/index.js下的Component下

  properties: {
    title: String,
    movies: Array
  },

components/movie/index.js下

 properties: {
    movie:Object
  }

步骤2:在wxml下把属性的值传进去

movies.wxml

 <movie-list title = "正在上映" movies="{{inTheaters}}" f-class="movie-list" />
<movie-list title="即将上映" movies="{{comingSoon}}" f-class="movie-list" />
<movie-list title="豆瓣TOP250" movies="{{top250}}" f-class="movie-list" />

可以看出 movies属性,titile属性都被赋值

movie-list组件的index.wxml

<view class="container f-class">
<view class = "title-container">
  <text>{{title}}</text>  
  <text class="more-content">更多 ></text>
</view>  
  <view class="movie-container">
  <block wx:for="{{movies}}" wx:key = "index">
    <movie movie="{{item}}" />
  </block>
  </view>
</view>

这一步也同时通过item把数据传进了movie
最后一个movie的wxml直接对数据展示即可,不再传递到别的组件/页面。

<view class="container">
    <image class="poster" src = "{{movie.images.large}}"></image>
    <text class="title">{{movie.title}}</text>
    <view class="rate-container">
    <l-rate inActive-color="blue" active-color="yellow" disabled="{{true}}" size="22" score = "{{movie.rating.stars}}/10"/>
    <text class="score">{{movie.rating.average}}</text>
    </view>
</view>

效果图

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lux Lin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值