“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 25 天,点击查看活动详情”
小程序-模板与配置
WXML模板语法---数据绑定
1.数据绑定的基本原则
- 在data里面定义数据
- 在WXML里面使用数据
2.在data里面定义页面
在页面对应的.js文件中,把数据定义到data对象中即可。
3.Mustache语法的格式
把data中的数据绑定到页面中渲染,使用Mustache语法(双大括号)将变量包起来即可。语法格式为:
代码如下:
<!--index.wxml-->
<!-- <view class="container">
<view class="userinfo">
<block wx:if="{{canIUseOpenData}}">
<view class="userinfo-avatar" bindtap="bindViewTap">
<open-data type="userAvatarUrl"></open-data>
</view>
<open-data type="userNickName"></open-data>
</block>
<block wx:elif="{{!hasUserInfo}}">
<button wx:if="{{canIUseGetUserProfile}}" bindtap="getUserProfile"> 获取头像昵称 </button>
<button wx:elif="{{canIUse}}" open-type="getUserInfo" bindgetuserinfo="getUserInfo"> 获取头像昵称 </button>
<view wx:else> 请使用1.4.4及以上版本基础库 </view>
</block>
<block wx:else>
<image bindtap="bindViewTap" class="userinfo-avatar" src="{{userInfo.avatarUrl}}" mode="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</block>
</view>
<view class="usermotto">
<text class="user-motto">{{motto}}</text>
</view>
</view> -->
<view>{{info}}</view>
// index.js
// 获取应用实例
// const app = getApp()
// Page({
// data: {
// motto: 'Hello World',
// userInfo: {},
// hasUserInfo: false,
// canIUse: wx.canIUse('button.open-type.getUserInfo'),
// canIUseGetUserProfile: false,
// canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
// },
// // 事件处理函数
// bindViewTap() {
// wx.navigateTo({
// url: '../logs/logs'
// })
// },
// onLoad() {
// if (wx.getUserProfile) {
// this.setData({
// canIUseGetUserProfile: true
// })
// }
// },
// getUserProfile(e) {
// // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
// wx.getUserProfile({
// desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
// success: (res) => {
// console.log(res)
// this.setData({
// userInfo: res.userInfo,
// hasUserInfo: true
// })
// }
// })
// },
// getUserInfo(e) {
// // 不推荐使用getUserInfo获取用户信息,预计自2021年4月13日起,getUserInfo将不再弹出弹窗,并直接返回匿名的用户个人信息
// console.log(e)
// this.setData({
// userInfo: e.detail.userInfo,
// hasUserInfo: true
// })
// }
// })
Page({
data:{
info: 'heollo world'
}
})
效果图如下:
4.Mustache语法的应用场景
该语法主要应用的场景如下:
- 绑定内容
- 绑定属性
- 运算(三元运算,算术运算)
5.动态绑定内容
页面的数据如下:
Page({
data:{
info: 'heollo world'
}
})
页面的结构如下:
<view>{{info}}</view>
6.动态绑定属性
页面的数据如下:
页面的结构如下:
7.三元运算
页面的数据如下:
页面的结构如下:
代码如下:
Page({
data:{
info: 'heollo world',
randomNum1: Math.random()*10
}
})
<view>{{randomNum1 >=5 ? '数字大于或者等于5':'数字小于5'}}</view>
运行结果如下:
“开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 25 天,点击查看活动详情”