微信小程序开发之路⑤

28、web-view 容器加载动作

可以用来承载网页的小程序

注意:
个人类型和海外类型无法使用

<view class="page-body">
    <view class="page-section page-section-gap">
        <web-view src="https://mp.weixin.qq.com/"></web-view>
    </view>
</view>

29、微信基础函数运用

Wx.canUse 判断小程序的 API,回调,参数,组件等是否在当前版本可用

返回:Boolean

参数:

${API} 代表 API 名字
${method} 代表调用方式,有效值为return, success, object, callback
${param} 代表参数或者返回值
${options} 代表参数的可选值
${component} 代表组件名字
${attribute} 代表组件属性
${option} 代表组件属性的可选值


<!--miniprogram/pages/funDemo/funDemo.wxml-->
<text>miniprogram/pages/funDemo/funDemo.wxml</text>

30、网络 API

// 上传
Wx.uploadFile
// 下载接口
downloadFile
下载进度变化监听
DownloadTask
传输操作接口
Request
监听传输操作接口
UploadTask
<button bindtap='requestOpt'>请求</button>
<button bindtap='requestAbort'>请求终止</button>
Page({
    requestUrl: 'https://www.baidu.com/s?w=苹果',
    requestTask: '',
    /**
     * 页面的初始数据
     */
    data: {},

    /**
     * 数据请求
     */
    requestOpt() {
        let that = this
        //request操作
        this.requestTask = wx.request({
            url: this.requestUrl,
            data: {},
            header: { 'content-type': 'application/json' },
            method: 'GET',
            dataType: 'json',
            responseType: 'text',
            success(res) {
                if (res.statusCode == 200) {
                    console.log('[success]', res.data)
                }
            },
            fail(res) {
                console.log('[fail]', res)
            },
            complete(res) {
                console.log('[complete]', res)
            },
        })
    },

    /**
     *  请求终止
     */
    requestAbort() {
        this.requestTask.abort()
    },
})

在后台设置合法域名

wx.downloadFile
<progress show-info percent='{{per}}'></progress>
<button bindtap='downloadOpt'>下载</button>
<view class='downloadImg'>
  <image src='{{imgPath}}'></image>
</view>
Page({
  filePath:'https://10.url.cn/qqcourse_logo_ng/ajNVdqHZLLCoujuprQQGTfyE96rgia1P9nwJzqeKdppgYXFicm3aVjP4gYJyiaKNWB13X5czgYuicvo/356',
  /**
   * 页面的初始数据
   */
  data: {
    imgPath:'',
    per:""
  },

  /**
   * 下载操作
   */
  downloadOpt(){
    let that = this
   const downloadTask =  wx.downloadFile({
      url:this.filePath,
      success(res){
        if(res.statusCode == 200){
          console.log('[success]',res)
          console.log(res.tempFilePath)
          that.setData({
            imgPath:res.tempFilePath
          })
        }
      },
      fail(res){
        console.log('[fail]', res);
      },
      complete(res){
        console.log('[complate]', res);
      }
    })
    //downloadTask.abort()
    downloadTask.onProgressUpdate((res)=>{
      console.log('下载进度',res.progress)
      console.log('已经下载的数据长度',res.totalBytesWritten)
      console.log('预期需要下载的数据总长度',res.totalBytesExpectedToWrite),
      that.setData({
        per: res.totalBytesWritten / res.totalBytesExpectedToWrite*100
      })
    })
  },
})
wx.uploadFile(Object object)

将本地资源上传到服务器。客户端发起一个 HTTPS POST 请求,其中 content-type 为 multipart/form-data。

<button bindtap="imgChoose">图片选择</button>

  imgChoose(){
    wx.chooseImage({  //图片的选择
      success: function(res) {
        const tempFilePaths = res.tempFilePaths //临时文件

        // 上传
        wx.uploadFile({
          url: 'http;//www.xxx.com', //公司的服务器地址
          filePath: tempFilePaths,
          name: 'pic1',
        },
        success((res)=>{
          console.log(res.data)
        })
        )
      },
    })

图灵机器人

31、websocket 的配置与操作

websocket 是
百度百科:WebSocket 是一种新的网络协议,他上线了客户端(异或浏览器)与服务器全双通讯

建立与服务器的通讯需要如下几个步骤

建立客户端与服务器之间的连接

监听服务器与客户端之间的动作

发送数据

将接受到的数据做处理

关闭连接

注意事项

服务器需要 ws 协议,不可以是 http 或 https

可以使用在线测试地址做操作

在线服务器位置: http://coolaf.com/tool/chattest

32、外部字体加载操作

通过网络加载本地没有的字体,来显示效果

加载通过 wx.loadFontFace 来完成

注意事项:

IOS 仅支持 https 格式文件地址

如果引入中文字体,体积过大会错误

原生组件不支持添加字体

33、微信录音 api

getRecordManager 返回 Manager 对象
开始录音
关闭录音
播放录音

<view>
    <button bindtap="start">开始录音</button>
    <button bindtap="stop">停止录音</button>
    <button bindtap="play">播放录音</button>
</view>

// 创建对象
const recorderManager = wx.getRecorderManager()
// 创建上下文
const innerAudioContext = wx.createInnerAudioContext()

Page({
    /**
     * 页面的初始数据
     */
    data: {},

    /**
     * 开始录音
     */
    start: function () {
        const options = {
            duration: 10000, //指定录音的时长,单位ms
            sampleRate: 16000, //采样率
            numberOfChannels: 1, //录音通道数
            encodeBitRate: 96000, //编码码率
            format: 'mp3', //音频格式,有效值 aac/mp3
            frameSize: 50, //指定帧大小,单位kb
        }

        //开始录音
        recorderManager.start(options)
        recorderManager.onStart(() => {
            console.log('recorder start')
        })
        recorderManager.onError((res) => {
            console.log(res)
        })
    },

    /**
     * 停止录音
     */
    stop() {
        recorderManager.stop()
        recorderManager.onStop((res) => {
            this.tempFilePath = res.tempFilePath
            console.log('停止录音', res.tempFilePath)
        })
    },

    /**
     * 播放录音
     */
    play() {
        innerAudioContext.autoplay = true
        ;(innerAudioContext.src = this.tempFilePath),
            innerAudioContext.onPlay(() => {
                console.log('开始播放')
            })
        innerAudioContext.onError((res) => {
            console.log('[error]', res)
        })
    },
})

34、外部字体加载操作

通过网络加载本地没有的字体,来显示效果
加载通过 wx.loadFontFace 来完成

注意事项:
IOS 仅支持 https 格式文件地址
如果引入中文字体,体积过大会错误
原生组件不支持添加字体

;<view class="container">
    <view class="page-body">
        <view class="page-section">
            <view class="page-body-info display-area {{ loaded ? 'font-loaded' : '' }}">
                <text wx:if="{{!loaded}}">Load {{ fontFamily }}</text>
                <text wx:else>{{ fontFamily }} is loaded</text>
            </view>
            <view class="btn-area">
                <button type="primary" bindtap="loadFontFace">
                    加载字体
                </button>
            </view>
        </view>
    </view>
</view>

Page({
    data: {
        fontFamily: 'Bitstream Vera Serif Bold',
        loaded: false,
    },

    onLoad() {
        this.setData({
            loaded: false,
        })
    },

    loadFontFace() {
        const self = this
        // 加载字体ttf
        wx.loadFontFace({
            family: this.data.fontFamily,
            source: 'url("https://sungd.github.io/Pacifico.ttf")',
            success(res) {
                console.log(res.status)
                self.setData({ loaded: true })
            },
            fail: function (res) {
                console.log(res.status)
            },
            complete: function (res) {
                console.log(res.status)
            },
        })
    },
})

35、微信小程序保存图片,获取图片

选择图片
chooseImage
获取图片信息
getImageInfo
预览图片
previewImage
保存图片值手机相册
saveImage

wx.saveImageToPhotosAlbum(Object object) 保存图片到系统相册。

<button bindtap='chooseImage'>获取图片</button>
<button bindtap='getImageInfo'>获取图片信息</button>
<button bindtap='previewImage'>预览图片</button>
<button bindtap='download'>下载图片</button>
<button bindtap='saveImg'>保存图片到相册</button>
<view>
<image class='img' src='{{updateImage}}' bindtap='previewImage'></image>
</view>
<view>
<image class='img' src='{{downloadFile}}' bindtap='previewImage'></image>
</view>

// pages/index/index.js
Page({
  chooseImgs:[],
  /**
   * 页面的初始数据
   */
  data: {
    updateImage:'',
    downloadFile:''
  },

  /**
   * 保存到本机相册
   */
saveImg(){
  wx.saveImageToPhotosAlbum({
    filePath: this.data.downloadFile,
    success(res){
      console.log("保存成功")
    }
  })
},



  /**
   * 获取图像
   */
  chooseImage(){
    let that = this
    wx.chooseImage({
      success(res) {
        that.chooseImgs = res.tempFilePaths
        console.log(res,"图片获取成功")

        that.setData({
          updateImage: res.tempFilePaths
        })
      }
    })
  },

  /**
   * 获取图片信息
   */
  getImageInfo(){
    wx.getImageInfo({
      src: this.chooseImgs[0],
      success(res){
        console.log(res)
      }
    })
  },
/**
 * 下载图片
 */
download(){
  var that = this;
  wx.downloadFile({
    url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg13.360buyimg.com%2Fn1%2Fjfs%2Ft1%2F106514%2F17%2F22537%2F54322%2F61ee5db4Eb96435e3%2Fd65b6ac4b4043b73.jpg&refer=http%3A%2F%2Fimg13.360buyimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1654044399&t=420a2ac93e4ed3508a27d664b4a95bfc', //仅为示例,并非真实的资源
    success (res) {
      // 只要服务器有响应数据,就会把响应内容写入文件并进入 success 回调,业务需要自行判断是否下载到了想要的内容
      // downloadFile: res.
      console.log(res)
      that.setData({
        downloadFile: res.tempFilePath
      })
    }
  })
},

  /**
   * 预览图片
   */
  previewImage(){
    wx.previewImage({
      urls: this.chooseImgs,
      current:'0'
    })
  }
})

36、loading 全操作

loading 有三种形式的显示

组件形式
loading
动态形式
ShowToast
showloading

;<view class="container">
    <view class="page-section">
        <view class="bold">loading组件</view>
        <loading hidden="{{loadingHidden}}">加载中....</loading>
    </view>
    <view class="page-section">
        <view class="bold">动态loading...(showToast)</view>
        <button bindtap="showToast">开启showToast</button>
    </view>

    <view class="page-section">
        <view class="bold">动态loading...(showLoading)</view>
        <button bindtap="showLoading">开启showToast</button>
    </view>
</view>

Page({
    /**
     * 页面的初始数据
     */
    data: {
        loadingHidden: true,
    },

    /**
     * showToast
     */
    showToast() {
        wx.showToast({
            title: 'loading',
            icon: 'loading',
            duration: 5000,
            mask: true,
            success(res) {},
            fail(res) {},
            complate(res) {},
        }),
            setTimeout(this.closeToastLoadin, 2000)
    },

    closeToastLoadin() {
        //关闭loading显示
        wx.hideToast()
    },

    /**
     * showLoading
     */
    showLoading() {
        wx.showLoading({
            title: '加载中...',
        }),
            setTimeout(this.closeLoading, 2000)
    },

    closeLoading() {
        wx.hideLoading()
    },
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值