美文网首页
周报 第二期

周报 第二期

作者: 水水壶 | 来源:发表于2019-07-28 22:47 被阅读0次

    这周主要是跟着慕课网学习做了一个小程序,开发小程序需要微信开发者工具。电影小程序

    一、 代码构成

    1、 json文件 配置文件

    • project.config.json 项目配置文件
    • app.json 全局配置文件
    • page.json 页面配置文件

    2、wxml 模板文件,描述页面结构,相当于html

    3、wxss 样式文件 调整页面样式,相当于css

    4、js 脚本逻辑文件,页面和用户的交互逻辑

    二、基本语法

    1、数据绑定

    小程序的数据一般情况下需要动态的从服务端获取然后渲染输出到视图中,wxml中的动态数据均来自于 page 中的 data,数据绑定使用 {{}} 将变量包起来

    <view> {{message}} </view>
    
    // page.js
    Page({
      data: {
        message: 'Hello MINA!'
      }
    })
    

    2、循环

    <view wx:for="{{arr}}" wx:key="{{index}}">{{item}}</view>
    // 用 wx:for 后面需要加 wx:key="{{index}}" 
    item 表示数组中的每一项
    index 表示每项中唯一的值
    

    3、 条件渲染

    1、用 wx:if 来判断是否需要渲染该代码模块,也可以用 wx:elifwx:else来添加一个 else 块

    <view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
    <view wx:elif="{{view == 'APP'}}"> APP </view>
    <view wx:else="{{view == 'MINA'}}"> MINA </view>
    
    // page.js
    Page({
      data: {
        view: 'MINA'
      }
    })
    
    

    2、 hidden

    <view hideen="{{ data  }}"> hello world</view>    // 当data的值为 ture ,hello world
    会被隐藏,当data的值为 fasle,hello world会被显示
    

    两者区别 :hidden 组件始终会被渲染,只是简单的控制显示与隐藏 ,wx:if只渲染 条件为 ture 的代码

    三 、wxss

    1、尺寸单位

    rpx,可以根据屏幕宽度进行自适应,适配不同宽度的屏幕


    image.png

    2、@import "common.wxss";

    使用@import语句可以导入外联样式表,@import后跟需要导入的外联样式表的相对路径,用;表示语句结束。

    3、使用第三方样式库

    先要初始化

    • 打开miniprogram 右键 ‘在终端打开’
    • $ npm init //在 miniprogram 文件夹中初始化一个文件,这步完成后可以看到在小程序 miniprogram 中生成一个 package.json文件
    • $ npm i vant -weapp -s --production 安装 vant 组件库 (在vant官网查看用法)
    • 回到小程序页面点击开发者工具,选择‘构建npm’
    • 点击开发工具最右边详情,勾选 ‘使用npm模块’

    这样才算完成引用第三方组件库

    四、云开发

    提供云函数、 云存储、 云数据库 三大基础能力


    image.png

    1、云数据库

    传统数据库和云数据库的区别

    1.1、数据类型

    • string 字符串
    • Number 数字
    • Object 对象
    • Array 数组
    • Bool 布尔
    • GeoPonit 地理位置点
    • Date 时间(是客户端的时间不是服务端的时间)
    • Null 空 (相当于占位符)

    1.2 操作云数据库

    操作数据库之前要首先对数据库进行初始化,然后在云开发中创建一个云数据库“user”集合

    const db = wx.cloud.datebase();          //初始化
    const testdb =  wx.cloud.datebase({   //切换环境
       env:'test'                                           //当前环境名称
    });
    //插入数据
    db.collection('user').add({
      data{                     //插入数据的属性和值
          name:'jack',
          age:20
    }
    })
    //更新数据
    db.collection('user').doc('id')            //id为唯一标识,知道更新的是哪一条数据
    .update({
      data{                     //更新数据的属性和值
          age:14
    }
    })
    
    //删除一条数据
    db.collection('user').doc('id')            //id为唯一标识,知道删除的是哪一条数据
    .remove()
    
    //查找数据
    db.collection('user').where({
    
    name:'jack'        // 查询name为jack这条数据
    }) .get()              // 通过 .get() 去获取这个用户
    

    注意:在小程序端是没有办法做到多条数据删除,只能做到单条数据的删除,想要多条数据删除要在云函数端去操作

    2、云函数

    云函数小程序写在云端的代码,相当于小程序的服务端后台代码,我们不需要去管理服务器,只需要在开发工具编写代码,通过一键上传部署代码,就可以运行代码,小程序的运行环境是 nodejs

    1. 创建云函数

    云函数根目录


    云函数根目录

    在根目录下右键新建 nodejs 云函数,然后输入云新建函数的名称

    exports.main = async (event, context) => {          // event 在调用云函数时小程序端传来的参数 context 调用的上下文,包括一些用户信息
       return {
        sum: event.a + event.b
      }
    }
    在云函数有改动的情况下 我们要上传并部署云函数
    

    2 .如何在小程序端调用云函数

     // 调用云函数
    wx.cloud.callFunction({    
      // 云函数名称
      name: 'add',
      // 传给云函数的参数
      data: {
        a: 1,
        b: 2,
      },
    })
    .then(res => {
      console.log(res.result)   // 3
    })
    .catch(console.error)
    

    3. 如何获取当前用户的 openid

    在小程序云函数中自带一个 login 这样的函数,它的作用就是获取当前用的的 OPENID、APPID、及 UNIONID


    login /index.js
    wx.cloud.callFunction({
      name: 'login ',
      complete: res => {
        console.log('callFunction login result: ', res)
      }
    })
    会在调试器看到输出的 res 为如下结构的对象:
    
    {
      "APPID": "xxx",
      "OPENID": "yyy",
      "UNIONID": "zzz", // 仅在满足 unionId 获取条件时返回
    }
    

    4. 如何通过云函数批量删除云数据库中的数据

    • 新建一个云函数 (batchDelete)
    const db = cloud.database();   // 获取到数据库
    exports.main = async  (event, context) => {
      return await  db.collection('user').where({       // 符合条件的信息
        name: 'jerry'
    }).remove();                                 // 删除符合条件的信息
    }
    
    

    async await 是对 js 异步操作的一种方式

    3. 云存储

    image.png

    1. 文件上传

    image.png

    首先我们要选择图片

    // 选择图片
    wx.chooseImage({
      count: 1,                                           // 当前选择图片个数,在小程序中最多支持是9张
      sizeType: ['original', 'compressed'], // original 以原文件形式上传 compressed 以压缩形式上传
      sourceType: ['album', 'camera'],       // album 文件来源于相册,camera文件来源于照相机
      success (res) {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths     // tempFilePaths 当前显示图片的临时路径
        wx.cloud.uploadFile({
        cloudPath: 'new Date().getTime() + .png', // 上传至云端的路径时间的毫秒数,保证上传的图片不会因重名被覆盖掉
        filePath: 'tempFilePaths[0]  ', // 小程序临时文件路径,这里 tempFilePaths 需要的是字符串而不是数组 
        success: res => {
        // 返回文件 ID
        console.log(res.fileID)
        db.collection('image').add({
         data {
                fileID : res.fileID
          }
            }).then(res=>{
                consle.log(res)
          }).catch(res=>{
            consle.error(err)
          })
      },
      fail: console.error
    })
      }
    })
    

    2. 如何展示图片

    <block wx:for="{{ imges }}" wx:key=" {{ index }} ">       // block 相当于 div 把对应的 wx:for 写在 block 上,其实 block 是不会显示在网页上 
      <image src=" "> </image src=" {{ item.fileID }}">
    <block>
    
    js
    data:{
    images:[]
    }
    // 查到刚才我这个用户上传的图片 
    wx.cloud.callFunction({
      name: 'login ', 
    }).then(res=>{    // res会返回 openid
        db.collection('image').where({
          -openid : res.result.openid
            }).get().then(res2=>{
             consle.log(res2)   // res2 是图片路径
              this.setdata ({
              images: res2.data
    
    })
     }) .catch(res=>{
            consle.error(err)
          })
    })
    

    3. 下载文件

    image.png
    <button data-fileid="{{ item.fileID }}" bindtap ="downloadFile"> 下载图片 </button> 
    js
    downloadFile:function(event){
      wx.cloud.downloadFile({
      fileID: 'event.target.dataset.fileid', // 获取当前文件fileID
      success: res => {
        // 返回临时文件路径
        console.log(res.tempFilePath)
    // 保存图片到手机相册
          wx.saveImageToPhotosAlbum({
             filePath:res.tempFilePath
            success(res) { 
              wx.showToast({    //表示在小程序中弹出一个框并在一定时间内消失掉
                  title:'保存成功',
    })
    }
    })
      },
      fail: console.error
    })
    }
    

    五、电影小程序的开发

    首先我们在电影首页要写个云函数拿到豆瓣电影数据,然后在小程序端调用云函数,把数据渲染到视图中,在电影评论页面我们需要把最新评论的信息存储到云数据库,在我的页面当中要通过 小程序 button 获取用户信息。

    1、云函数拿到豆瓣电影数据

    首先我们要在云函数目录下建立一个文件夹为 movielist 在这个目录下右键打开终端 下载安装

    $ npm install --save request
    $ npm install --save request-promise
    
    
    // 在云函数文件中
    const cloud = require('wx-server-sdk')
    
    cloud.init()  // 初始化 cloud
    var rp = require('request-promise');
    
    // 云函数入口函数
    exports.main = async (event, context) => {
     console.log(event)  // console.log 的内容可以在云开发云函数调用日志查看
    
     return rp(`http://api.douban.com/v2/movie/in_theaters?apikey=0df993c66c0c636e29ecbb5344252a4a&start=${event.start}&count=${event.count}`)  // 查询豆瓣电影接口 
       .then(function (res) {
         console.log(res);
         return res;
       })
       .catch(function (err) {
         console.err(err);
       });
    }
    
    

    2、在小程序中调用云函数

    data: {
        movieList:[],
      },       // 传到页面数据 
    // 调用云函数
     wx.cloud.callFunction({    
          name: "movielist",   // 云函数名字
          data:{                       // 传给云函数的参数
            start: this.data.movieList.length,  
            count: 10,
          }
        }).then(res => {             // 成功后
          console.log(res);
          this.setData({               // 给 data里数据赋值 
            movieList: this.data.movieList.concat(JSON.parse(res.result).subjects)
          })
          wx.hideLoading()
        }).catch(err => {            // 失败后
          console.error(err);
          wx.hideLoading()
        });
    

    3、在小程序中把数据渲染到视图中

    <view class='movie' wx:for="{{movieList}}" wx:key="{{index}}">   // 循环movieList
      <image class="movie-img" src="{{item.images.small}}"></image>
      <view class="movie-info">
        <view class="movie-title">{{ item.title }}</view>
        <view> 观众评分:
          <text class="movie-scope"> {{item.rating.average}}分</text>
        </view>
        <view> 主演:
          <text wx:for="{{item.casts}}" wx:key="{{index}}"> {{item.name}}</text>
        </view>
        <view>年份:{{ item.year }}</view>
      </view>
      <button bindtap="gotoComment" data-movieid= "{{ item.id }}" class="movie-comment">评价</button> 
    </view>
    
    

    4、获取用户信息

    <view class="user-info">
      <image class="user-img" src="{{ userUrl}}"></image>
      <view class='user-name'> {{ userName }} </view>
    </view>
    <button open-type="getUserInfo" bindgetuserinfo="onGotUserInfo">获取用户信息</button>
    //js
     data: {
        userUrl: '',
        userName: '',
      },
     onGotUserInfo: function (event) {
        console.log(event.detail.userInfo)
        this.setData({
          userUrl: useinfo.avatarUrl,
          userName: useinfo.nickName,
        })
      },
    

    相关文章

      网友评论

          本文标题:周报 第二期

          本文链接:https://www.haomeiwen.com/subject/lohyrctx.html