当前位置:主页 > 查看内容

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

发布时间:2021-05-27 00:00| 位朋友查看

简介:1.尝试访问服务端数据 在onLoad函数下添加 wx.request({url: http://... }) 比想象的简单很多有没有 接下来在控制台打印一下看看服务器返回的数据的详情。 wx.request({url: http://... suceess(res){console.log(res)}}) res参数这个参数请不要慌张就是由服……

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>

效果图

;原文链接:https://blog.csdn.net/weixin_46728068/article/details/115534269
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文


随机推荐