您的位置:时时app平台注册网站 > 编程知识 > Wechat小程序实战–集阅读与电影于风流倜傥体的

Wechat小程序实战–集阅读与电影于风流倜傥体的

2019-11-28 03:24

26.越来越多电影页面数据加载

util.js

function http(url, callback) {
  wx.request({
    url: url,
    method: 'GET',
    header: {
      'content-type': 'json' 
    },
    success: function (res) {
      callback(res.data)
    }
  })
}

module.exports = {
  convertToStarArray: convertToStarArray,
  http: http,
};

more-movie.js

var util = require('../../../utils/util.js')
var app = getApp();
Page({
  data:{
    categoryTitle: '',
    movies: {},
  },
  onLoad: function (options) {
    var category = options.category;
    this.data.categoryTitle = category;
    var dataUrl = ''
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.g_baseUrl   "/v2/movie/in_theaters";
        break;
      case "即将上映":
        dataUrl = app.globalData.g_baseUrl   "/v2/movie/coming_soon";
        break;
      case "豆瓣Top250":
        dataUrl = app.globalData.g_baseUrl   "/v2/movie/top250";
        break;
    }
    util.http(dataUrl, this.processDoubanData)
  },

  processDoubanData:function(data){
    var movies = [];
    for (var idx in data.subjects) {
      var subject = data.subjects[idx]
      var title = subject.title;
      if (title.length >= 6) {
        title = title.substring(0, 6)   "...";
      }
      var temp = {
        stars: util.convertToStarArray(subject.rating.stars),
        title: title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      movies.push(temp)
    }
    this.setData({
      movies: movies
    });
  },

  onReady: function () {
    wx.setNavigationBarTitle({
      title: this.data.categoryTitle,
    })
  },
})

movie-grid-template.wxml

<import src="../movie/movie-template.wxml" />
<template name="movieGridTemplate">
  <view class="grid-container">
    <block wx:for="{{movies}}" wx:for-item="movie">
      <view class="single-view-container">
        <template is="movieTemplate" data="{{...movie}}" />
      </view>
    </block>
  </view>
</template>

movie-grid-template.wxss

@import "../movie/movie-template.wxss";

/*scroll-view*/
.single-view-container{
    float:left;
    margin-bottom: 40rpx;
}

.grid-container{
    height: 1300rpx;
    margin:40rpx 0 40rpx 6rpx;
}

more-movie.wxml

<import src="../movie-grid/movie-grid-template.wxml" />
<template is="movieGridTemplate" data="{{movies}}" />

more-movie.wxss

@import "../movie-grid/movie-grid-template.wxss";

预览

时时app平台注册网站 1

27.完结上海好笑剧团加载越来越多多少

movie-grid-template.wxml

<import src="../movie/movie-template.wxml" />
<template name="movieGridTemplate">
  <scroll-view class="grid-container" scroll-y="true" scroll-x="false" bindscrolltolower="onScrollLower">
    <block wx:for="{{movies}}" wx:for-item="movie">
      <view class="single-view-container">
        <template is="movieTemplate" data="{{...movie}}" />
      </view>
    </block>
  </scroll-view>
</template>

more-movie.js

var util = require('../../../utils/util.js')
var app = getApp();
Page({
  data:{
    categoryTitle: '',
    movies: {},
    requsetUrl: '',
    isEmpty: true,
    totalCount: 0
  },
  onLoad: function (options) {
    .
    .
    .
    this.data.requsetUrl = dataUrl;
    util.http(dataUrl, this.processDoubanData)
  },

  processDoubanData:function(data){
   .
   .
   .

    var totalMovies = {}
    if (!this.data.isEmpty) {
      totalMovies = this.data.movies.concat(movies)
    } else {
      totalMovies = movies
      this.data.isEmpty = false
    }
    this.setData({
      movies: totalMovies
    })
    this.data.totalCount  = 20;
  },

  onScrollLower:function(event){
    var nextUrl = this.data.requsetUrl   
    "?start="   this.data.totalCount   "&count=20";
    util.http(nextUrl,this.processDoubanData)
  },

接着上文继续~(上文地址:)
深入分析:"正在热映"和"将在热映"的电影列样式基本风姿浪漫致,只是多少不平等,因而思忖以自定义组件的点子落实四个手拉手页面,供二者使用。

25.动态设置导航栏标题

more-movie.js

// pages/movies/more-movie/more-movie.js
Page({
  data:{
    categoryTitle: '',
  },
  onLoad: function (options) {
    var category = options.category;
    this.data.categoryTitle = category;
    console.log(category);
  },
  onReady: function () {
    wx.setNavigationBarTitle({
      title: this.data.categoryTitle,
    })
  },
})

29.实现下拉刷新

more-movie.json

{
  "enablePullDownRefresh": true
}

more-movie.js

onPullDownRefresh: function () {
    var refreshUrl = this.data.requsetUrl  
      "?star=0&count=20";
    this.data.movies = {};
    this.data.isEmpty = true;
    this.data.totalCount = 0;
    util.http(refreshUrl, this.processDoubanData);
    wx.showNavigationBarLoading();
  },

  processDoubanData:function(data){
    .
    .
    .
    this.data.totalCount  = 20;
    wx.hideNavigationBarLoading()
    wx.stopPullDownRefresh()
  },

自定义组件

  1. 创制components文件夹,创制新的页面movieList,如下图所示:
![](https://upload-images.jianshu.io/upload_images/10954635-42bb506c2897e8b3.png)

由于movieList是叁个组件,必要在movieList.json中布局如下代码:

{
  "component": true
}
  1. movieList组件是用以home页面中的,在home.json中注册这么些组件,代码如下:
{
  "usingComponents": {
    "movieList": "../../components/movieList/movieList"
  }
}
  1. 安排完以上之后就足以在home页面调用了,home.wxml代码如下:
 <view class="page">
  <view class="nav">
    <view class="{{homeSelected?'current':'default'}}" bindtap="handleHomeSelected">正在热映</view>
    <view class="{{comingSelected?'current':'default'}}" bindtap="handleComingSelected">即将上映</view>
  </view>
  <view class="{{homeSelected?'show':'hidden'}}">
    <!-- 正在热映 -->
     <movieList id="movieList" sendValue="{{movieType}}"></movieList> 
  </view>
  <view class="{{comingSelected?'show':'hidden'}}">
      <!-- 即将上映 -->
     <movieList id="movieComingList" sendValue="{{movieType}}"></movieList>   
  </view> 
</view> 

id代表唯意气风发标记值,可以取到这一个组件;value表示传到movieList页面包车型地铁参数key,名称能够自定义

  1. 组件中的方法、属性使用甚至拿到传递过来的参数
Component({
  properties: {
    'sendValue':{ //与home.wxml中的key值对应
      type: String, //必填,属性类型,包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: "" , //属性初始值
      observer: function (newVal, oldVal) { //属性值被更改时的响应函数
         //...
      }
    }
  },
  data: {
    //...
  },
  methods: {
    //...
  }
})

获得传递过来的参数:this.properties.sendValue

24.愈来愈多电影

app.json

"pages": [
    "pages/posts/post",
    "pages/welcome/welcome",
    "pages/posts/post-detail/post-detail",
    "pages/movies/movies",
    "pages/movies/more-movie/more-movie"
  ],

more-list-template.wxml

 <view class="more" catchtap='onMoreTap' data-category="{{categoryTitle}}">
          <text class="more-text">更多</text>
          <image class="more-img" src="/images/icon/arrow-right.png"></image>
        </view>

movies.js

 onMoreTap:function(event){
    var category = event.currentTarget.dataset.category;
    wx.navigateTo({
      url: 'more-movie/more-movie?category='   category
    })
  },

more-movie.js

// pages/movies/more-movie/more-movie.js
Page({

  onLoad: function (options) {
    var category = options.category;
    console.log(category);
  },
})

分级点击更多,能够见到相应的分类

时时app平台注册网站 2

28.设置loading状态

more-movie.js

onScrollLower: function (event) {
    var nextUrl = this.data.requsetUrl  
      "?start="   this.data.totalCount   "&count=20";
    util.http(nextUrl, this.processDoubanData);
    wx.showNavigationBarLoading()
  },

  processDoubanData:function(data){
    .
    .

    this.setData({
      movies: totalMovies
    })
    this.data.totalCount  = 20;
    wx.hideNavigationBarLoading()
  },

时时app平台注册网站 3

30.电影搜索效果完成

movies.wxml

<import src="movie-list/movie-list-template.wxml" />
<import src="movie-grid/movie-grid-template.wxml" />
<view class="search">
  <icon type="search" class="search-img" size="13" color="#405f80"></icon>
  <input type="text" placeholder="西虹市首富" placeholder-class="placeholder" bindfocus="onBindFocus" bindconfirm="onBindBlur"/>
   <image wx:if="{{searchPanelShow}}" src="/images/icon/xx.png" class="xx-img" bindtap="onCancelImgTap"></image> 
</view>
.
.

<view class="search-panel" wx:if="{{searchPanelShow}}">
    <template is="movieGridTemplate" data="{{...searchResult}}"/>
</view>

movies.wxss

@import "movie-grid/movie-grid-template.wxss";

.search {
  background-color: #f2f2f2;
  height: 80rpx;
  width: 100%;
  display: flex;
  flex-direction: row;
}

.search-img {
  margin: auto 0 auto 20rpx;
}

.search input {
  height: 100%;
  width: 600rpx;
  margin-left: 20px;
  font-size: 28rpx;
}

.placeholder {
  font-size: 14px;
  color: #d1d1d1;
  margin-left: 20rpx;
}

.search-panel{
    position:absolute;
    top:80rpx;
}

.xx-img{
    height: 30rpx;
    width: 30rpx;
    margin:auto 0 auto 10rpx;
}

movies.js

Page({
  data: {
    inTheaters: {},
    comingSoon: {},
    top250: {},
    searchResult: {},
    containerShow: true,
    searchPanelShow: false
  },

    onBindFocus: function (event) {
    this.setData({
      containerShow: false,
      searchPanelShow: true
    })
  },
  onCancelImgTap: function (event) {
    this.setData({
      containerShow: true,
      searchPanelShow: false,
      searchResult: {}
    })
  },

  onBindBlur: function (event) {
    var text = event.detail.value
    var searchUrl = app.globalData.g_baseUrl   "/v2/movie/search?q="   text;
    this.getMovieList(searchUrl, "searchResult", "");
  },

结果

时时app平台注册网站 4

拿到电影列表

  1. 编辑movieList.wxml
 <view class="page">
  <block wx:if="{{showLoading}}">
      <view class="page-loading">
        <image class="loading-img" src="../..loading.gif" />
        <text>玩命加载中...</text>
      </view>
    </block>
  <block wx:else>
    <scroll-view style="height:1100px;" scroll-y="{{true}}" scroll-top="0" 
    bindscrolltolower="handleScrollToLower">
      <block wx:for="{{list}}" wx:key="{{index}}">
        <view class="list" data-id="{{item.id}}" bindtap="handleRedirect">
          <view class="left">
            <image src="{{item.images.large}}" />
          </view>
          <view class="middle">
            <view class="row row-title">
              {{item.original_title}}
            </view>
            <view class="row row-content">
              评分:{{item.rating.average}}
            </view>
            <view class="row row-content">
              导演:<view wx:for="{{item.directors}}" wx:for-item="directors" wx:key="{{index}}">
                {{directors.name}}
              </view>
            </view>
            <view class="row row-content">
              主演:<view wx:for="{{item.casts}}" wx:for-item="casts" wx:key="{{index}}">
                {{casts.name}} <text wx:if="{{index 1-item.casts.length < 0}}">/</text>
              </view>
            </view>  
          </view>
          <view class="right right-content">
            <text>{{item.reviews_count}}人看过</text>
            <button class="right-content-btn" bindtap="handleBuyTicket">购票</button>   
          </view>
        </view>
      </block>

      <block wx:if="{{showMore}}">
        <view class="page-loading">
            <image class="loading-img" src="../..loading.gif" />
            <text>玩命加载中...</text>
          </view>
      </block>
      <block wx:else>
        <view class="page-loading">
           <text>没有更多内容了</text> 
        </view>
      </block>
    </scroll-view>
  </block>    
 </view>
  1. 编写样式文件movieList.wxss

"正在热播"和"就要热映"的样式同样,成立二个styles文件夹,再次创下立公共样式文件movieLayout.wxss,代码如下:

.list{
  display:flex;
  border-bottom: 1px solid #dfdfdf;
}
.left{
  width:25%;
  margin-left:20rpx
}
.left image{
  width:100%;
  height:280rpx;
}
.middle{
  width:55%; 
  margin-right:20rpx 
}
.right{
  width:20%;
}
.left,.middle,.right{
  height:280rpx;
  margin-bottom:20rpx;
  margin-top:20rpx;
}
.row{
   width:100%; 
   margin:0 5rpx 5rpx 15rpx;  
}
.row-title{
  font-size:15px;
  font-weight: bold;
}
.row-content,.right-content,.right-content-btn{
   font-size:12px;
}
.row view{
  display: inline-block;
  padding-right:5rpx;
}
.right-content{
    color:#F76D61;
    margin-right:10rpx;
}
.right-content-btn{
  border: 1px solid #F76D61;
  color:#F76D61;
  margin-top:20rpx;
  margin-left:0;
  width:130rpx;
  height:55rpx;
  line-height:55rpx;
  background-color: #ffffff;
}

在movieList.wxss文件中引进公共样式movieLayout.wxss:

@import "../../styles/movieLayout";

.page{
  margin-top:80rpx;
  height:100%;
}
.page-loading{
  display:flex;
  text-align: center;
  justify-content: center;
  align-items: center;
  padding-top:10rpx;
}
.page-loading .loading-img{
  margin-right:5rpx;
  width:30rpx;
  height:30rpx;
}
.sv{
  height:1000rpx;
}
  1. 编写制定样式文件movieList.js

那边必要寻访接口获取数据, 在utils文件夹下创建api.js,封装访谈接口的方式,获取数据,代码如下:

var API_URL = 'http://t.yushu.im/v2/movie';

function fetchApi(type,params){
  return new Promise((resolve,reject)=>{
    wx.request({
      url: `${API_URL}/${type}`, //模板字符串
      data: params,
      header: {
        'content-type': 'application/json' 
      },
      success: resolve,
      fail: reject
    })
  })
}

//http://t.yushu.im//v2/movie/in_theaters?start=0&count=20
module.exports = {
  //获取电影列表
  getList(type,start=0,count=20){
    return fetchApi(type, {"start": start*count,"count":count})
      .then(res=>res.data)
  },
  //获取电影详情
  getDetail(id){
    return fetchApi("/subject/" id)
      .then(res=>res.data)
  }
}

movieList.js代码:

var api = require('../../utils/api')

Component({
  properties: {
    'sendValue':{
      type: String, //必填,目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型)
      value: "" , 
      observer: function (newVal, oldVal) {
        this.setData({
          list: [],//电影列表
          start: 0
        })
      }
    }
  },
  data: {
    start: 0,
    list: [],
    showLoading: true,
    showMore: true
  },
  methods: {
    loadData(start) {
      console.log(this.properties.sendValue) 
      //http://t.yushu.im/v2/movie/in_theaters?start=0&count=20
      api.getList(this.properties.sendValue, start)
        .then(res => {
          if (res.subjects.length > 0) {
            this.setData({
              list: this.data.list.concat(res.subjects),//连接前面一页的数据
              showLoading: false,
              showMore: true,
              start: start   1 //页数递增
            })
          } else {
            this.setData({
              showMore: false
            })
          }
        })
    },
    handleScrollToLower(e) {
      //如果没有更多的数据就不再加载
      if (!this.data.showMore) {
        return;
      }
      this.loadData(this.data.start);
    },
    handleRedirect(e) {
      var id = e.currentTarget.dataset.id;
      //电影详情页面跳转并传入当前id值 下一篇文章会详细讲解 这里的代码现在可以注释
      wx.navigateTo({
        url: '../../pages/detail/detail?id='   id,
      })
    },
    handleBuyTicket(e){
      console.log("点击了购票按钮");
    },
  }
})
  1. 在home.wxml中引进movieList.wxml组件,并在home.js中调用加载列表数据的主意。

home.wxml:

 <view class="page">
  <view class="nav">
    <view class="{{homeSelected?'current':'default'}}" bindtap="handleHomeSelected">正在热映</view>
    <view class="{{comingSelected?'current':'default'}}" bindtap="handleComingSelected">即将上映</view>
  </view>
  <view class="{{homeSelected?'show':'hidden'}}">
     <!-- 正在热映 -->
     <movieList id="movieList" sendValue="{{movieType}}"></movieList> 
  </view>
  <view class="{{comingSelected?'show':'hidden'}}">
     <!-- 即将上映 -->
     <movieList id="movieComingList" sendValue="{{movieType}}"></movieList>   
  </view> 
</view>  

home.js:

var api = require('../../utils/api')

Page({
  data: {
    homeSelected:true,
    comingSelected:false,
    movieType:'' //传到movieList.wxml组件的参数
  },
  //转发页面
  onShareAppMessage(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '来自豆瓣电影',
      path: '/pages/index/index',
      success: function (res) {
        console.log('转发成功')
      },
      fail: function (res) {
        console.log('转发失败')
      }
    }
  },
  handleHomeSelected(e){
    this.setData({
      homeSelected: true,
      comingSelected: false,
      movieType: 'in_theaters'
    })
    //调用movieList子组件的方法
    this.movieList = this.selectComponent("#movieList");
    this.movieList.loadData(0);//起始页为0
  },
  handleComingSelected(e) {
    this.setData({
      homeSelected: false,
      comingSelected: true,
      movieType: 'coming_soon'
    })
    this.movieList = this.selectComponent("#movieComingList");
    this.movieList.loadData(0);
  },
  onReady: function () {
    this.handleHomeSelected();
  } 

到这里电影列表获取就到位啦~
最后还剩贰个得到电影详细情形的页面,当中第一会波及到横向滚动组件的应用,下风姿罗曼蒂克篇三番三回~
即使文中有啥样狼狈的只怕需求小心之处应接大家指正,一同享用调换~

本文作品权归我全体,如需转发,请联系小编并证明出处及原链接。

本文由时时app平台注册网站发布于编程知识,转载请注明出处:Wechat小程序实战–集阅读与电影于风流倜傥体的

关键词: