微信小程序开发入门篇(二)

✍、目录

配套视频教程:B站直达

微信小程序🔥地址
微信小程序开发入门篇(一)🔥https://blog.csdn.net/Augenstern_QXL/article/details/121489385
微信小程序开发入门篇(二)🔥https://blog.csdn.net/Augenstern_QXL/article/details/121620224

1、WXML语法

1.1、数据绑定

WXML 中的动态数据均来自对应 Page 的 data。

  1. 页面.js 中的 data 选项中初始化数据
Page({
   data: {
     msg: '大林',
     listArr:["UI","web","java","Go"],
     obj:{
       name: "大林",
       age: 20,
       sex: "男"
      }
    },
})
  1. 页面.wxml 中使用数据
<!-- wxml -->
<view>{{msg}}</view>
<view>{{listArr}}</view>
<view>{{listArr[0]}}-{{listArr[1]}}-{{listArr[2]}}--{{listArr[3]}}</view>
<view>
  {{obj.name}}
  {{obj.age}}
  {{obj.sex}}
</view>

在这里插入图片描述

1.1.1、组件属性(需要在双引号之内)

<!-- wxml -->
<view id="item-{{id}}"> </view>

<!-- js -->
Page({
  data: {
    id: 0
  }
})

1.1.2、控制属性(需要在双引号之内)

<!-- wxml -->
<view wx:if="{{condition}}"> </view>

<!-- js -->
Page({
  data: {
    condition: true
  }
})

1.1.3、关键字

<!-- wxml -->
<checkbox checked="{{false}}"> </checkbox>

特别注意:不要直接写 checked="false",其计算结果是一个字符串,转成 boolean 类型后代表真值。

1.1.4、运算

可以在 {{}} 内进行简单的运算,支持的有如下几种方式

  • 三元运算
<view hidden="{{flag ? true : false}}"> Hidden </view>
  • 算数运算
<!-- wxml -->
<view> {{a + b}} + {{c}} + d </view>

<!-- js -->
Page({
  data: {
    a: 1,
    b: 2,
    c: 3
  }
})

view中的内容为 3 + 3 + d

  • 逻辑判断
<view wx:if="{{length > 5}}"> </view>
  • 字符串运算
<!-- wxml -->
<view> {{"hello" + name}} </view>

<!-- js -->
Page({
  data: {
     name: 'MINA'
  }
})

1.1.5、修改数据

  • this.setData
Page({

  /**
   * 页面的初始数据
   */
  data: {
      msg: '大林'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
      console.log(this);  // this代表当前页面的实例对象
      console.log(this.data.msg); // 大林
      // 修改 msg 的状态数据,语法 this.setData
      this.setData({
        msg: '修改之后的大林'
      })
      
  },
}

在这里插入图片描述

onLoad: function (options) {
  console.log(this);  // this代表当前页面的实例对象
  console.log(this.data.msg); // 大林
  // 修改 msg 的状态数据,语法 this.setData
  setTimeout(()=>{
    this.setData({
      msg: '修改之后的大林'
    })
  },2000)

},

如果我们使用定时器延时 2s 然后进行修改,那么 2s 后依然会修改数据

1.2、条件渲染

1.2.1、wx:if

  • 使用 wx:if="" 来判断是否需要渲染该代码块:
<!-- wxml -->
<view wx:if="{{1<2}}">大林1</view>
<view wx:if="{{1>2}}">大林2</view>

<view>--------------</view>
<view wx:if="{{true}}">大林3</view>
<view wx:if="{{false}}">大林4</view>

也可以用 wx:elifwx:else 来添加一个 else 块:

<!-- wxml -->
<view wx:if="{{day==1}}">周一</view>
<view wx:elif="{{day==2}}">周二</view>
<view wx:elif="{{day==3}}">周三</view>
<view wx:elif="{{day==4}}">周四</view>
<view wx:elif="{{day==5}}">周五</view>
<view wx:elif="{{day==6}}">周六</view>
<view wx:else>错误</view>

1.2.3、block wx:if

  • 因为 wx:if 是一个控制属性,需要将它添加到一个标签上。
  • 如果要一次性判断多个组件标签,可以使用一个 <block/> 标签将多个组件包装起来,并在上边使用 wx:if 控制属性。
<!-- wxml -->
<block wx:if="{{true}}">
  <view> view1 </view>
  <view> view2 </view>
</block>
<blocl wx:else>
  <view> view3 </view>
</blocl>

注意: <block/> 并不是一个组件,它仅仅是一个包装元素,不会在页面中做任何渲染,只接受控制属性。

1.3、列表渲染

1.3.1、wx:for

  • 在组件上使用 wx:for 控制属性绑定一个数组,即可使用数组中各项的数据重复渲染该组件。
  • 默认数组的当前项的下标变量名默认为 index,数组当前项的变量名默认为 item
<!-- wxml -->
<!-- index 为索引值,item 是数组中的每一项 -->
<view wx:for="{{listArr}}">
  {{index}}|{{item}}
</view>

<!-- js -->
Page:({
  data: {
	 listArr:["java","Go","web","python","C++"]
  }
})
  • 使用 wx:for-index 可以指定当前元素的变量名
  • 使用 wx:for-item 可以指定当前元素的变量名
<!-- 使用 wx:for-index 可以指定当前元素的变量名 -->
<!-- 使用 wx:for-item 可以指定当前元素的变量名 -->
<view wx:for="{{listArr}}" wx:for-index="i">
  {{i}}|{{item}}
</view>

在这里插入图片描述

如果我们 data 中的数据是对象类型

<!-- wxml -->
<view wx:for="{{listObj}}">
  <text>{{item.title}}</text> - <text>{{item.time}}</text>
</view>

<!-- js -->
Page:({
  data: {
	 listObj: [
        {
          title:"标题",
          time:"2021-09-18"
        },{
          title:"标题2",
          time:"2021-09-18"
        },{
          title:"标题3",
          time:"2021-09-18"
        }
      ]
  }
})

1.3.2、wx:key

  • 我们在使用 wx:for 时,最好加一个 wx:key='*this'
  • 或者加一个 wx:key="index"
<!-- wxml -->
<view wx:for="{{listObj}}" wx:key="index">
  <text>{{item.title}}</text> - <text>{{item.time}}</text>
</view>

<!-- 或着 -->
<view wx:for="{{listObj}}" wx:key="*this">
  <text>{{item.title}}</text> - <text>{{item.time}}</text>
</view>

2、WXSS样式

2.1、小程序适配方案

  • 小程序适配单位:rpx (responsive pixel 响应式像素单位)
  • 规定任何屏幕下宽度为 750rpx
  • 在iPhone 6 下 1rpx = 0.5px,小程序会根据屏幕的宽度不同自动计算 rpx 值的大小
  • 我们一般设计规范都是依据 iPhone 来设计的,也就是说平时 UI 设计师给出的 1px 我们写代码时要写 0.5rpx。(也就是用 px / 2 来得到我们对应的 rpx 大小)。

2.2、样式导入

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

/** common.wxss **/
.small-p {
  padding:5px;
}
/** app.wxss **/
@import "common.wxss";
.middle-p {
  padding:15px;
}

2.3、内联样式

框架组件上支持使用 style、class 属性来控制组件的样式。

  • style:静态的样式统一写道 class 中。
<view style="color:{{color}};" />
  • class:用于指定样式规则,其属性值是样式规则中类选择器名(样式类名)的集合,样式类名不需要带上.,样式类名之间用空格分隔。
<view class="normal_view" />

目前支持的选择器有:

选择器样例样例描述
.class.intro选择所有拥有 class=“intro” 的组件
#id#firstname选择拥有 id=“firstname” 的组件
elementview选择所有 view 组件
element, elementview, checkbox选择所有文档的 view 组件和所有的 checkbox 组件
::afterview::after在 view 组件后边插入内容
::beforeview::before在 view 组件前边插入内容

需要注意的是小程序是不支持通配符 *

3、事件

事件分为冒泡事件和非冒泡事件:

  1. 冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
  2. 非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递。

冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。

例如:我们使用 bindtap 来绑定事件

<!-- wxml -->
<view bindtap="clickParent">
  <text bindtap="clickChild">点击</text>
</view>


<!-- js -->、
Page({
  clickParent(){
    console.log("Parent")
  },

  clickChild(){
    console.log("child")
  },

})

在这里插入图片描述

如果我们使用 catchtap 来绑定事件

<!-- wxml -->
<view catchtap="clickParent">
  <text catchtap="clickChild">点击</text>
</view>


<!-- js -->、
Page({
  clickParent(){
    console.log("Parent")
  },

  clickChild(){
    console.log("child")
  },

})

在这里插入图片描述

总结:

  • bind 绑定:事件绑定不会阻止冒泡事件向上冒泡
  • catch 绑定:事件绑定可以阻止冒泡事件向上冒泡

3.1、事件分类

事件分为冒泡事件和非冒泡事件:

  1. 冒泡事件:当一个组件上的事件被触发后,该事件会向父节点传递。
  2. 非冒泡事件:当一个组件上的事件被触发后,该事件不会向父节点传递。

WXML的冒泡事件列表:

类型触发条件
touchstart手指触摸动作开始
touchmove手指触摸后移动
touchcancel手指触摸动作被打断,如来电提醒,弹窗
touchend手指触摸动作结束
tap手指触摸后马上离开
longpress手指触摸后,超过350ms再离开,如果指定了事件回调函数并触发了这个事件,tap事件将不被触发
longtap手指触摸后,超过350ms再离开(推荐使用longpress事件代替)
transitionend会在 WXSS transition 或 wx.createAnimation 动画结束后触发
animationstart会在一个 WXSS animation 动画开始时触发
animationiteration会在一个 WXSS animation 一次迭代结束时触发
animationend会在一个 WXSS animation 动画完成时触发
touchforcechange在支持 3D Touch 的 iPhone 设备,重按时会触发

3.2、点击事件bindtap

我们如果想给一个组件定义点击事件,就要用到bindtap,我们给一个组件绑定点击事件的语法如下。

<!-- 在wxml里给组件定义点击事件的语法 -->
<button bindtap="click">点我</button>

我们给一个组件定义点击事件,主要是给组件定义一个 bindtap=“事件名”,然后再js页面里定义和事件名一样的函数即可。

Page({
  click(){
    console.log("点击了按钮");
  },
})

在这里插入图片描述

3.3、获取用户输入信息bindinput

  • 在wxml里定义好bindinput事件以后,在js页面再定义一个和事件名一样的函数即可。
<input bindinput="getContent" placeholder="请输入内容"></input>
Page({
  getContent(options){
     console.log(options);
     console.log(options.detail.value);				// 获取输入框的内容
  }
})

在这里插入图片描述

如果我们前端传递一个 data-title 的数据,都存在事件对象的 currentTarget 里面(data-x 属性是H5里面特有的

<!-- wxml -->
<button bindtap="click" data-title="微信小程序">按钮</button>

在这里插入图片描述

3.4、修改数据

  • 如果要修改 data 里面的数据,必须使用 this.setData({message:'修改之后的数据'},callback)
<!-- wxml -->
<button bindtap="click">{{name}}</button>

<!-- js -->
Page({
    data: {
		name: '大林'
	},
	click(res){
		// 修改数据
		this.setData({
  			name: '小林'
	})
},
})

4、API

API 非常之多,我们也没有必要每一个都学,来看下我们常用的。

4.1、wx.getSystemInfoSync()

<!-- wxml -->
<button bindtap="click">{{name}}</button>

<!-- js -->
Page({
    data: {
		name: '大林'
	},
	click(res){
		console.log(wx.getSystemInfoSync())
	})
},
})

在这里插入图片描述

4.2、wx.showLoading

<!-- wxml -->
<button bindtap="click">{{name}}</button>

<!-- js -->
Page({
    data: {
		name: '大林'
	},
	click(res){
		wx.showLoading({
      		title: '加载中',
    	}),
        setTimeout(function () {
  			wx.hideLoading()
		}, 2000)
	})
},
})

在这里插入图片描述

4.3、wx.showToast

<!-- wxml -->
<button bindtap="click">{{name}}</button>

<!-- js -->
Page({
    data: {
		name: '大林'
	},
	click(res){
		wx.showToast({
      		title: '成功',			// 信息框文本
      		icon: 'success',		 // 显示成功图标
      		duration: 2000			 // 提示的延迟时间
    	})
	})
},
})

在这里插入图片描述

注意:wx.showLoading 和 wx.showToast 同时只能显示一个

4.4、wx.request

wx.request({
   url: 'https://edu.newsight.cn/wxList.php',		// 接口地址
   data:{},
   success:(res)=>{
      console.log(res);
   }
 })

我们可以通过 wx.request 发起 HTTPS 网络请求,请求成功可以拿到返回的数据

在这里插入图片描述

<!-- wxml -->
<view class="out">
  <view class="row" wx:for="{{resData}}" wx:key="index">
  <view class="pic">
    <image src="{{item.picurl}}" mode="widthFix"></image>
  </view>
  <view class="text">
    <view class="title">{{item.title}}</view>
    <view class="time">{{item.posttime}} - {{item.author}}</view>
  </view>
</view>

</view>


<!--wxss-->
.out{
  padding: 30rpx;
  box-sizing: border-box;
}

.row {
  display: flex;
  height: 200rpx;
  margin-bottom: 20rpx;
}
.pic{
  flex: 2
}
.pic image{
  width: 100%;
  height: 100%;
}
.text{
  flex: 8
}

<!--js-->
onLoad: function (options) {
 wx.request({
   url: 'https://edu.newsight.cn/wxList.php',
   data:{

   },
   success:(res)=>{
      this.setData({
        resData: res.data,
      })
   }
 })

},

在这里插入图片描述

如果接口失效,json 数据如下,我们可以新建 .json 文件,在 wx.request 的请求路径 url 中写入此文件路径即可。

[{\
	"id": "1644",
	"title": "视频剪辑越来越卡?掌握这些技巧让你的剪辑快如闪电!",
	"author": "李宝娟",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210915\/1631695678.jpg",
	"posttime": "1631687162"
}, {
	"id": "1643",
	"title": "Web前端这个行业前景到底如何?能不能挣到钱?",
	"author": "王士进",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210827\/1630054195.png",
	"posttime": "1630048692"
}, {
	"id": "1641",
	"title": "学影视后期,什么样的电脑能带你起飞?",
	"author": "张继鹏",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210818\/1629287922.jpg",
	"posttime": "1629279053"
}, {
	"id": "1640",
	"title": "只需四步,帮你搞定设计中的标题文字",
	"author": "汪瑶",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210806\/1628223461.jpg",
	"posttime": "1628214953"
}, {
	"id": "1639",
	"title": "教你12招,让设计细节更高级",
	"author": "王士进",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210729\/1627548870.jpg",
	"posttime": "1627545127"
}, {
	"id": "1638",
	"title": "那些你不知道的C4D建模技巧",
	"author": "李贝贝",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210721\/1626857068.png",
	"posttime": "1626853617"
}, {
	"id": "1636",
	"title": "室内设计中的新中式与传统中式",
	"author": "王光英",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210715\/1626337416.jpg",
	"posttime": "1626333774"
}, {
	"id": "1635",
	"title": "详解设计中的图文排版技巧",
	"author": "刘长安",
	"picurl": "http:\/\/nsedu.oss-cn-beijing.aliyuncs.com\/images\/20210707\/1625623469.png",
	"posttime": "1625620686"
}, {
	"id": "1634",
	"title": "电商APP设计原则",
	"author": "王付栋",
	"picurl": "https:\/\/newsight.oss-cn-qingdao.aliyuncs.com\/images\/2016\/2.jpg?Expires=1625130871&OSSAccessKeyId=LTA",
	"posttime": "1625126285"
}]

5、生命周期

我们来看微信开发工具自动帮我们生成的 页面.js 文件中的代码

Page({

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

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
属性类型说明
onLoad(Object options)function在页面加载时触发。一个页面只会调用一次
onShow()function页面显示/切入前台时触发。会执行多次
onReady()function页面初次渲染时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。
onHide()function页面隐藏/切入后台时触发。
onUnload()function页面卸载时触发
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

生命是有光的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值