乌市泽哥 发表于 4 天前

微信小程序开发第三课

1 wxml语法

1.1 模版语法

#1 在页面 xx.js 的 Page() 方法的 data 对象中进行声明定义
#2 在xx.wxml 中使用 {{}} 包裹,显示数据
#3 可以显示如下,不能编写js语句或js方法
        -变量
        -算数运算
        -三元运算
        -逻辑判断
   
# 4 只是单纯通过赋值,js中变量会变化,但是wxml中的页面不会变化,没有联动效果,需要使用setData()方法修改
        - 更新数据
    - 页面更新

# 5 setData案例 修改数字
## 5.1 wxml
<view>
<view>姓名是:{{name}}</view>
<view>年龄是:{{age}}</view>
<button bind:tap="handleAddAge" plain="true" type="primary" size="mini">点击增加年龄</button>
</view>
##5.2 js
handleAddAge(){
    //this.data.age++
    console.log(this.data.age)
    this.setData({
      age:this.data.age+1
    })
},

   
# 6 setData案例 修改对象
## 6.1 wxml<view>
<view>姓名是:{{userinfo.name}}</view>
<view>年龄是:{{userinfo.age}}</view>
<view>爱好是:{{userinfo.hobby}}</view>
<button bind:tap="handleChangeName" plain="true" type="primary" size="mini">点击修改对象-姓名</button>
</view>

## 6.2 js
    data: {
      name: 'justin',
      age: 19,
      userinfo: {
          name: 'lqz',
          age: 99
      }
      },

handleChangeName() {
    // 增加数据
    this.setData({
      'userinfo.hobby': '篮球'
    })
    // 修改数据
    this.setData({
      'userinfo.name': '彭于晏'
    })

    // 修改多个数据--》简便方案--》展开运算符
    // const userinfo = {
    //   ...this.data.userinfo,
    //   name: '新名字',
    //   hobby: '乒乓球'
    // }
    // this.setData({
    //   // userinfo:userinfo
    //   userinfo //简写形式
    // })
    // 修改多个数据--》简便方案-->assign
    const userinfo = Object.assign(this.data.userinfo, {
      name: 'xxzz',
      hobby: '烫头'
    })
    this.setData({
      // userinfo:userinfo
      userinfo //简写形式
    })

    //删除数据-->单个
    delete this.data.userinfo.name // 页面删除不了,需要用setData更新
    this.setData({
      userinfo:this.data.userinfo
    })

    //删除数据-->多个--解构赋值
    const {name,age,...res}=this.data.userinfo
    this.setData({
      userinfo:res
    })

},

   
# 7 setData 修改数组
## 7.1 js
data: {
    names:['刘亦菲','迪丽热巴','古力娜扎','马尔扎哈']
},
   
   handleChangeList(){
    //1 增加数组
    // 1.1 增加再设置值
    this.data.names.push('亚瑟王')
    this.setData({
      names:this.data.names
    })

    // 1.2 通过数组拼接
    // const newList=this.data.names.concat("甄姬")
    // this.setData({
    //   names:newList
    // })

    // 1.3 通过解构赋值
    const newList=[...this.data.names,"李白"]
    this.setData({
      names:newList
    })

    // 2 修改数组
    this.setData({
      'names':'justin'
    })

    // 3 删除数组
    this.data.names.slice(1)
    this.setData({
      names:this.data.names.slice(1)
    })


},
## 7.2 wxml
<view wx:for="{{names}}" wx:key="index">
{{item}}

</view>
<button bind:tap="handleChangeList" plain="true" type="primary" size="mini">修改数组</button>
   
   
# 8 双向数据绑定:input checkbox
<view>
<!-- 不支持数组和对象 -->
<input type="text" model:value='{{name}}' style="border:orange solid 1rpx"/>
<checkbox model:checked="{{isCheck}}"/>
<text>{{isCheck}}</text>
</view>



1.2 列表渲染

# 1 基本使用
## 1.1 js
data: {
    goodsList:[{id:1001,name:'钢笔',price:9},{id:1002,name:'铅笔',price:6},{id:1003,name:'脸盆',price:99}]
},
##1.2 wxml

<view>
<!-- wx:key 提升性能,不写会警告可以用 index或 *this:代指item本身要唯一-->
<view wx:for="{{goodsList}}" wx:key="*this">
<!-- 默认每个对象是item,默认每个下标是index -->
<!-- <text>商品id:{{item.id}}--商品名字:{{item.name}}--商品价格:{{item.price}}</text> -->
</view>
</view>
# 2 修改wx:for-indexwx:for-item
<view>
<view wx:for="{{goodsList}}" wx:key="*this" wx:for-item="info">
<!-- 修改默认index和item--wx:for-indexwx:for-item    -->
<text>商品id:{{info.id}}--商品名字:{{info.name}}--商品价格:{{info.price}}</text>
</view>
</view>

# 3 block
<block>商品id:{{info.id}}--商品名字:{{info.name}}--商品价格:{{info.price}}</block>
1.3 条件渲染

# 1 wx:if   wx:elif   wx:else
<view>
<input type="text" model:value='{{score}}' style="border:orange solid 1rpx"/>


<view wx:if="{{score>=90&&score<=100}}">优秀</view>
<view wx:if="{{score>=80&&score<90}}">良好</view>
<view wx:if="{{score>=60&&score<80}}">及格</view>
<view wx:else="{{score>=90&&score<=100}}">不及格</view>
</view>


# 2 wx:if和 hidden
## 2.1 js
showPhoto:true,
showPhotoHidden:true
    handleShowPhoto(){
      this.setData({
            showPhoto:!this.data.showPhoto
      })
      console.log(this.data.showPhoto)
    },
    handleShowPhotoHidden(){
      this.setData({
            showPhotoHidden:!this.data.showPhotoHidden
      })
    },
   
## 2.2 wxml
<view>
<image src="/images/b.jpg" mode="widthFix" wx:if="{{showPhoto}}"/>
<button bind:tap="handleShowPhoto" plain="true" type="primary" size="mini">显示隐藏图片(if)</button>
<view></view>
<image src="/images/b.jpg" mode="widthFix" hidden="{{showPhotoHidden}}"/>
<button bind:tap="handleShowPhotoHidden" plain="true" type="primary" size="mini">显示隐藏图片(hidden)</button>
</view>
二 发送网络哀求

2.1 wx.request()

# 1 发送网络请求的域名,必须在微信公众平台配置
        -本地环境去除,只适用于开发版和体验版
# 2 发送请求
handleLoadData(){
    wx.showLoading({
      title: '加载中,稍后',
      mask:true// 显示透明蒙层
    })
    wx.request({
      url: 'http://192.168.71.100:5000',
      method:'GET',
      data:{},
      header:{},
      success:(res)=>{
      wx.hideLoading()
      console.log(res.data)
      this.setData({
          userinfo:res.data,
      })
      console.log(this.data.name)
      },
      fail:(err)=>{},
      complete:(res)=>{}

    })
},

https://i-blog.csdnimg.cn/direct/1266ef461ce14be18fe83f16f46db4d5.png#pic_center
2.2 loading提示框

# 显示
wx.showLoading({
      title: '加载中,稍后',
      mask:true// 显示透明蒙层
    })
   
   
#关闭
wx.hideLoading()
三 对话框

3.1 模态对话框

##### wxml
<button type="default" size="mini" bind:tap="showModel">弹出模态框</button>
### js ###
showModel(){
    wx.showModal({
      title: '这是标题',
      content: '这是内容部分~~',
      complete: (res) => {
            if (res.cancel) {
                console.log('用户取消了')
            }

            if (res.confirm) {
                console.log('用户确认了')
            }
      }
    })
}
3.2 消息对话框

#### wxml
<button type="default" size="mini" bind:tap="showToast">弹出消息框</button>
### js
showToast(){
    wx.showToast({
      title: '恭喜您,秒杀成功',
      icon:"success",
      duration:2000
    })
}
四 存储

#### wxml####
<button type="default" plain bind:tap="handleSave">存储数据</button>
<button type="primary" plain bind:tap="handleGet">获取数据</button>
<button type="default" plain bind:tap="handleDelete">删除数据</button>
<button type="primary" plain bind:tap="handleClear">清空数据</button>
###js### 同步####
handleSave() {
    wx.setStorageSync('name', "justin")
    wx.setStorageSync('userinfo', {name:'lqz',age:19})
},
handleGet() {
    const name=wx.getStorageSync('name')
    const userinfo=wx.getStorageSync('userinfo')
    console.log(name)
    console.log(userinfo)
},
handleDelete() {
    wx.removeStorageSync('name')
},
handleClear() {
    wx.clearStorageSync()
}

###js### 异步####
handleSave() {
    wx.setStorage({
      key:'name',
      data:"justin"
    })
    wx.setStorage({
      key:'userinfo',
      data:{name:'lqz',age:19}
    })
},

async handleGet() {
    const name= await wx.getStorage({key:'name'})
    const userinfo= await wx.getStorage({key:'userinfo'})
    console.log(name)
    console.log(userinfo)
},
handleDelete() {
    wx.removeStorage({key:'name'})
},
handleClear() {
    wx.clearStorage()
}
五 上拉下拉加载

5.1 下拉加载

### wxml####
<view wx:for="{{goods}}" wx:key="index">{{item}}</view>

### wxss###
view{
height: 400rpx;
display: flex;
justify-content: center;
align-items: center;
}
/* 奇数 */
view:nth-child(odd){
background-color: pink;
}
/* 偶数 */
view:nth-child(even){
background-color: green;
}
   
##### js######
// 监听上拉下载更多
onReachBottom(){
console.log('上拉了')
// 发送请求,加载数据
wx.request({
    url: 'http://192.168.71.100:5000',
    method:'GET',
    success:(res)=>{
      console.log(res)
      this.setData({
      goods:this.data.goods.concat(res.data)
      })
      
    }
})

}

####json####
{
"usingComponents": {},
"onReachBottomDistance": 50 # 到达底部距离
}

### 后端flask###
from flask import Flask,jsonify
import random
app=Flask(__name__)
@app.route('/',methods=['GET'])
def index():
    l=[]
    for i in range(3):
      l.append(random.randint(0,9))
    return jsonify(l)


if __name__ == '__main__':
    app.run(host='0.0.0.0')
5.2 下拉刷新

### json####
{
"usingComponents": {},
"onReachBottomDistance": 50,
"enablePullDownRefresh": true, # 开启下拉刷新
"backgroundColor": "#efefef", #下拉刷新背景色
"backgroundTextStyle":"dark" # 下拉刷新点颜色
}
#### wxml###
<view wx:for="{{goods}}" wx:key="index">{{item}}</view>
###js###
// 下拉刷新
onPullDownRefresh(){
console.log('下拉了')
this.setData({
    goods:
})
// 在下拉刷新后,loading效果可能没回弹
if(this.data.goods.length==3){
    wx.stopPullDownRefresh()
}
}
5.3 使用 scroll-view实现

##### wxml####
<scroll-view
class="scroll"
scroll-y# 运行y轴滑动
lower-threshold="100" # 距离底部还有100px时,触发事件
bindscrolltolower="handleGetData"# 事件处理函数


refresher-enabled="true"      # 开启 下拉刷新
refresher-default-style="black" # 下拉默认样式
refresher-background="#f0f0f0"# 下拉背景色
bindrefresherrefresh="handleReload" # 下拉触发事件
refresher-triggered="{{isRefresh}}" # 设置下拉回弹,false允许回弹,

enable-back-to-top="true"# 快速回到顶部,ios点顶部,安卓点tab
>
<view wx:for="{{goods}}" wx:key="index">{{item}}</view>
</scroll-view>


### json###
{
"usingComponents": {}
}

###wxss###
.scroll{
/* 100vh就是指元素的高度等于当前浏览器的视窗高度,即浏览器内部的可视区域的高度大小 */
height: 100vh;
background-color: grey;
}

view{
height: 400rpx;
display: flex;
justify-content: center;
align-items: center;
}
/* 奇数 */
view:nth-child(odd){
background-color: pink;
}
/* 偶数 */
view:nth-child(even){
background-color: green;
}
   
   
#### js####
data: {
    goods:,
    isRefresh:false
},
handleGetData(){
    console.log('上拉了')
    // 发送请求,加载数据
    wx.request({
      url: 'http://192.168.71.100:5000',
      method:'GET',
      success:(res)=>{
      console.log(res)
      this.setData({
          goods:this.data.goods.concat(res.data)
      })
      
      }
    })
},
handleReload(){
    console.log('下拉刷新了')
    wx.showToast({
      title: '下拉刷新',
    })
    this.setData({
      goods:
    })
    this.setData({
      isRefresh:false
    })
}
六 更新和生命周期

6.1 小程序更新

# 1 访问小程序,微信会将小程序代码包,下载到微信本地,打开使用
# 2 当小程序更新版本后,微信会检查小程序版本有没有更新,并下载最新小程序
# 3 更新方式:启动时同步更新,启动时异步更新
        ### 同步更新:
    -启动时同步更新:微信运行时,会定期检查最近使用的小程序是否有更新。如果有更新,下次小程序启动时会同步进行更新,更新到最新版本后再打开小程序。如果 用户长时间未使用小程序时,会强制同步检查版本更新
        -如果更新失败,还是会使用本地版本
        -新版本发布24小时后,基本会覆盖全部用户
    ### 异步更新####
    启动时异步更新:在启动前没有发现更新,小程序每次 冷启动 时,都会异步检查是否有更新版本。如果发现有新版本,将会异步下载新版本的代码包,将新版本的小程序在下一次冷启动进行使用,当前访问使用的依然是本地的旧版本代码
    ## 强制更新###
    在启动时异步更新的情况下,如果开发者希望立刻进行版本更新,可以使用 wx.getUpdateManager API 进行处理。在有新版本时提示用户重启小程序更新新版本
   
# 4 在app.js中加入
App({
// 生命周期函数,启动小程序就会执行
onLaunch(){
    const update=wx.getUpdateManager()
    update.onUpdateReady(function(){
      wx.showModal({
      title: '发现新版本',
      content: '重启应用,更新版本新版本?',
      success:(res)=>{
          if(res.confirm){
            update.applyUpdate()
          }
      }
      })
    })
}
})
https://i-blog.csdnimg.cn/direct/91e209b9d17d4df2b9f8dbf4787a11fe.png#pic_center
6.2 应用生命周期

// app.js
App({

/**
   * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
   */
onLaunch: function () {
    console.log('小程序启动了')
   
},

/**
   * 当小程序启动,或从后台进入前台显示,会触发 onShow
   */
onShow: function (options) {
    console.log('后台切前台了')
},

/**
   * 当小程序从前台进入后台,会触发 onHide
   */
onHide: function () {
    console.log('进后台了')
},

})

6.3 页面生命周期

Page({

/**
   * 生命周期函数--监听页面加载
   */
onLoad(options) {
    console.log('1 页面加载了')

},

/**
   * 生命周期函数--监听页面初次渲染完成
   */
onReady() {
    console.log('3 初次渲染完成')
},

/**
   * 生命周期函数--监听页面显示
   */
onShow() {
    console.log('2 页面显示')
},

/**
   * 生命周期函数--监听页面隐藏
   */
onHide() {
    console.log('4 页面隐藏')
},

/**
   * 生命周期函数--监听页面卸载
   */
onUnload() {
    console.log('5 页面卸载')
},


})
七 其他

7.1 分享到朋友圈

// 允许发送到朋友圈,右上角 ... 分享到朋友圈
onShareTimeline(){
    return {
      title:"这是一个神奇的页面",
      query:'name=justin&age=19',
      imageUrl:'/images/b.jpg'
    }
},
7.2 转发

# 1 方式一:通过右上方 ...
# 2 方式二:通过按钮, 需要给button设置 open-type="share"
<button open-type="share">转发</button>
# 3 js中编写
onShareAppMessage() {
    return {
      title:"是朋友就点一下",
      path:"/pages/my/my", //当前转发的页面
      imageUrl:'/images/b.jpg'
    }

},

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 微信小程序开发第三课