微信小程序常用语句

本文用于记录学习微信小程序常用语句。


前言

笔者跟着编程小石头学习微信小程序的开发,是为了便于物联网的控制。


1、给文本添加点击事件,感知按下功能。

//index.wxml
<text bindtap="dianyingyuan">电影院</text>
<text bindtap="waipojia">外婆家</text>

//index.js
Page({
  dianyingyuan(){
    console.log("电影院开始放电影啦。")
  },
  waipojia(){
    wx.showToast({
      icon:'none',//提示无√
      title: '外婆喊你吃饭了',
    })
  }
})

2、提示

//index.wxml
wx.showToast({
	icon:'none',//提示无√
	title: '外婆喊你吃饭了',
})
//加载中
wx.showLoading({
	title: '加载中...',
})
//隐藏加载中
wx.hideLoading()

3、input组件

关于占位符、占位符颜色、默认值、输入字符类型的设置

//index.wxml
<input placeholder="我是输入框" placeholder-style="color:#F76260" value="我是默认的输入内容" type="number"></input>

4、button组件

//index.wxml
<button type="primary" plain="true">我是按钮</button>
<button loading="true">我是加载按钮</button>

5、多个button组件用同一个点击事件

//index.wxml
<button bindtap="getData" data-page="1">加载第一页</button>
<button bindtap="getData" data-page="2">加载第二页</button>
<button bindtap="getData" data-page="3">加载第三页</button>

//index.js
getData(e)
{
	console.log(e.currentTarget)
}

6、image组件

当没有设置宽高时,image组件的默认宽度是320px,高度是240px。

//index.wxml
<image lazy-load mode="aspectFill" src="url"></image >//懒加载 保持横纵比 只保证短边能完全显示出来

7、选择图片

//index.js
wx.chooseImage({
	count:1,//可以选择多少张图片
	sizeType:['original','compressed'],
	sourceType:['album','camera'],//设置图片来源
	success(res){
	//tempFilePath可以作为img标签的src属性显示图片
	const tempFilePaths=res.tempFilePaths
})

8、video组件

//index.wxml
<video duration="1" autoplay src="url"></video>//视频时长 自动播放

9、函数书写格式

//index.js
Page({
  onLoad(){
    console.log("onload执行了")
    this.hanshu1()
    this.hanshu2()
  },
  //函数的两种定义方法
  hanshu1(){
    console.log("我是函数定义的方式,简写版")
  },
  hanshu2:function(){
    console.log("我是函数定义的方式,复杂版")
  }
})

10、更改页面导航标题

//index.json
"navigationBarTitleText":"列表刷新"

11、获取用户输入内容

//index.wxml
<input bindinput="getContent" placeholder="请输入内容"></input>

//index.js
getContent(neirong){
    // console.log("执行了getContent")
    console.log(neirong.detail.value)
  }

12、使用es6语法避免this指向问题

//index.js
wx.getUserProfile({
	desc:'必须授权才可以继续使用',
	success:res=>{
		this.setData({
		nickName:res.userInfo.nickName
		})
	},
	fail:res={
	console.log('授权失败')
	}
)}

13、动态数据显示

//index.wxml
<text>{{name}}</text>

//index.js
Page({
  data:{//页面的初始数据
    name:""
  },
  onLoad(){
    this.setData({
      name:"ztx"
    })
  }
})

14、登录本地缓存的实现

使用wx.setStorageSync存缓存
使用wx.getStorageSync取缓存

//index.js
wx.setStorageSync({key:"key",
data:"value"})
wx.getStorageSync('key')
wx.setStorageSync('key',null)//清空本地缓存

15、按钮全局撑满

在app.json中把"style": "v2"删掉

16、打开另外一个小程序

//index.js
wx.navigateToMiniProgram({
	appId:'appId',
})

17、使用tabBar来配置2-5个页面

//app.json
  "tabBar": {
    "color": "#000000",
    "selectedColor": "#000000",//字体选中颜色
    "list": [{
      "pagePath": "page/index/index",
      "text": "首页",
      "iconPath": "image/home-no.png",//不支持网络图标
      "selectedIconPath": "image/home-yes.png"
    }, {
      "pagePath": "page/car/car",
      "text": "购物车",
      "iconPath": "image/car-no.png",
      "selectedIconPath": "image/car-yes.png"
    },{
      "pagePath": "page/me/me",
      "text": "我的",
      "iconPath": "image/me-no.png",
      "selectedIconPath": "image/me-yes.png"
    }]
  },
  "usingComponents": {}

18、页面跳转

//index.wxml
<navigator url="/pages/detail/detail" open-type="navigate">默认跳转方式跳转到新页面</navigator>//返回到刚刚页面 不能跳转到tabbar页面
<navigator url="/pages/detail/detail" open-type="redirect">跳转到新页面</navigator>//返回到首页 不能跳转到tabbar页面
//switchTab 跳转到tabbar页面,并关闭所有非tabbar页面
//reLaunch关闭所有页面,打开到应用中的某一个页面
//navigateBack关闭当前页面,返回上一页面或多级页面
//exit退出小程序,target="miniProgram"时生效

wx.navigateTo({url:'/pages/detail/detail',})
wx.redirectTo({url:'/pages/detail/detail',})
wx.switchTab ({url:'/pages/detail/detail',})
wx.reLaunch({url:'/pages/detail/detail',})
wx.navigateBack({url:'/pages/detail/detail',})

//list.wxml
<view wx:for="{{list}}">
	<view class="item" bindtap="goNew" data-title="{{item}}>{{item}}</view>
</view>

//list.js
Page({
	data:{
	list:[
		'新闻标题1''新闻标题2''新闻标题3'
	]
	},
	//去新闻详情页
	goNew(e){
		let title=e.currentTarget.dataset.name
		let name='ztx'
		let age=18
		console.log('点击了新闻标题',title)
		wx.navigateTo({url:'/pages/detail/detail?title'+title,})//携带一个参数
		wx.navigateTo({url:'/pages/detail/detail?title='+title+'&name='+ztx+'&age='18,})//携带多个参数
	}
})

//detail.js
Page({
	onLoad(options){
		console.log('详情页',options)
	}
})

19、通过switchTab跳转tarbbar页面如何携带数据

19-1、通过app.js里的globalData

//app.js
globalData:{
	name:null,
	userInfo:null
}

//list.js
const app=getApp()
Page({
	goDetail(){
		app.globalData.name='ztx'//app.globalData.name={name='ztx',age=18}
		console.log('点switchTab 跳转',app.globalData.name)
		wx.switchTab ({url:'/pages/car/car',
		})	
	}
)}

//car.js
const app=getApp()
Page({
	onLoad(options){
		console.log('传递参数',app.globalData.name)
	}
})

19-2、通过本地缓存

//list.js
goDetail(){
//let obj={name='ztx',age=18}
	wx.setStorageSync('title','ztx')
}
//car.js

Page({
	onLoad(options){
		console.log('传递参数',wx.getStorageSync('title'))
	}
})

20、页面下拉触底

//index.js
onReachBottom(){
	console.log('onPullDownRefresh')
}

21、页面下拉刷新

//index.json
"window":{
	"enablePullDownRefresh":true//开启下拉刷新
	"backgroundColor":"#d3d3d3"
}
//index.js
onPullDownRefresh(){
	console.log('onPullDownRefresh')
	//刷新动画的停止
	wx.stopPullDownRefresh()
	//刷新动画的开启
	wx.startPullDownRefresh()
}

22、条件页面渲染

//index.wxml
<text wx:if="{{score>=90}}">成绩优秀</text>
<view wx:elif="{{score>=60}}">成绩及格</view>
<view wx:else="{{score<60}}">成绩不及格</view>

//index.js
Page({
  data:{
    score:10
  },
  onLoad(){
  }
})

23、数组定义和添加、删除元素,数组索引

//index.wxss
var name=new Array()//数组创建第一种方式
var name=['张三','李四','王五']//数组创建第二种方式
name[3]='小朱'//添加数组元素
name.push(小朱)//在数组末尾添加元素
name.pop()//在数组末尾删除元素
name.unshirft('小朱')//在数组开头添加元素
name.shirf()//在数组末尾删除元素
name.indexOf('张三')//从前往后的第一个索引。如果张三存在数组,得到张三在数组中的第一个位置,否则返回-1 lastIndexOf从后往前的第一个索引
//把数组转换成字符串
//toString()将数组通过逗号连接成字符串
//join(分隔符)将数组通过分隔符连接成一个字符串,分隔符不写,默认用逗号来连//接数组元素
var arr=[1,3,2,5,4]
arr.toString()//1,3,2,5,4
arr.join('-')//1-3-2-5-4

//两个数组相连
let arr1=[1,2,3]
let arr2=[4,5,6]
arr1=arr1.concat(arr2)//1,2,3,4,5,6

24、对象的三种创建方法

//第一种:利用字面量创建对象
    // var ztx={
    //   name:'ztx',
    //   fun(){
    //     console.log('ztx会写代码')
    //   }
    // }
    // console.log(ztx.name)
    // ztx.fun()
    //第二种:利用new Object()创建对象
    // var ztx=new Object()
    // ztx.name='ztx'
    // ztx.fun=function(){
    //   console.log('ztx会写代码')
    // }
    // console.log(ztx.name)
    // ztx.fun()
    //第三种:利用构造函数创建对象
    function Person(name,age){
      this.name=name;
      this.age=age;
      this.fun=function(log){
          console.log(log)
      }
    }
    var obj1=new Person('ztx',18)
    console.log(obj1.name)
    obj1.fun('ztx会写代码')

25、javaScript自带内置对象文档链接

MND教程:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript
w3school教程:https://www.w3school.com.cn/js/index.asp
菜鸟教程:https://www.runoob.com/js/js-tutorial.html

26、css文档链接

菜鸟教程:https://www.runoob.com/css/css-tutorial.html
w3school教程:https://www.w3school.com.cn/css/index.asp

27、wxss常用样式

//index.wxss
//文本常用对齐方式
text-align:center;//文本居中 left right
//文本修饰
text-decoration:overline;//上划线 line-through underline
//设置字体大小
font-size:35px;
//padding内边距:上右下左
padding:10px 20px 30px 40px;
padding-top:10px;//padding-right padding-bottom padding-left 
//border边框
border:yellow solid;//黄色的·实线的·边框 
border-style:dashed;虚线
borser-width:10px
//margin外边距
//设置宽、高
width:100px;
height:100px;
//border-radius设置圆角边框
border-radius:10px;//当有宽高设置为50%或者宽高一半实现圆形
color:red;
margin-bottom:40px;
background:yello;//背景色
//css自由布局
display:flex;
flex-direction:column;//从上自下
//justify-content:center;
align-items:center;//横向居中

28、wxml中定义class选择器和在wxss中实现css样式。

.wxml主要用于布局组件,.wxss主要用于设计显示样式,.js主要用于处理逻辑。

//index.wxml
<view class="style">样式</view>

//index.wxss
.style{
  background-color: green;
}

29、RGB颜色对照表

https://tool.oschina.net/commons?type=3

30、搜索框示例

在这里插入图片描述

//index.wxml
<view class="root">
  <view class="son">搜索</view> 
</view>

//index.wxss
.root{
  background: #ffb965;
  padding: 10px;
}
.son{
  background: white;
  border-radius: 15px;
  text-align: center;
  color: gainsboro;
}

31、rpx是微信小程序专门设计的一个尺寸单位。

一般设计规范是依据iPhone6设计,ui设计师给出1px写代码时要写0.5px。开发小程序最好使用rpx作为小程序的尺寸单位,这样能很好地做自适应。

32、初始化云开发环境

// app.js
App({
  onLaunch(){
    wx.cloud.init({
      env:'study-qy-1gjjxcvj121f1395'
    })
  }
})

33、在project.config.json配置云函数所在目录为cloud。

//project.config.json
"cloudfunctionRoot": "/cloud",

34、右击云函数目录新建node.js云函数

35、数据库搜索

wx.cloud.database().collection('news').where({
	title:'ztx'
	}).get()
	.then(res=>{
      console.log('云函数调用成功',res)
    })
    .catch(res=>{
      console.log('云函数调用失败',res)
    })

36、数据库模糊搜索

//模糊搜索单个字段
let db=wx.cloud.database()
db.collection('news').where({
	title:db.RegExp({
		regexp:'ztx',//匹配字段
		options:'i',//不区分大小写
		})
	})
	.then(res=>{
      console.log('云函数调用成功',res)
    })
    .catch(res=>{
      console.log('云函数调用失败',res)
    })
//模糊搜索多个字段
let db=wx.cloud.database()
let _=db.command
db.collection('news')
	.where(_.or([{//.and同时满足
		title:db.RegExp({
			regexp:'ztx',模糊搜索字段
			options:i,
			})
		},
		{
			title:db.RegExp({
				regexp:'18',模糊搜索字段
				options:i,
			})
		}
	]))
	.then(res=>{
      console.log('云函数调用成功',res)
    })
    .catch(res=>{
      console.log('云函数调用失败',res)
    })

37、调用云函数

//yunhanshu.js
Page({
  onLoad(){
    //云函数的调用
    let that=this
    wx.cloud.callFunction({
      name:'getData',
      success(res){
        console.log('请求云函数成功',res)
        that.setData({
          openid:res.result.openid
        })
      },
      fail(err){
        console.log('请求云函数失败',err)
      }
    })
  }
})

//第二种云函数调用写法
Page({
  onLoad(){
    //云函数的调用
    wx.cloud.callFunction({
        name:'getData',
      })
      .then(res=>{
        console.log('云函数调用成功',res)
        this.setData({
          openid:res.result.openid
        })
      })
      .catch(res=>{
        console.log('云函数调用失败',res)
      })
  }
})

38、调用云函数修改数据

注意:云函数只要有变动,就要重新部署,否则云函数不生效。

//demo1.js
var id=''
Page({
  data:{
    good:{}
  },
  onLoad(options){
    console.log('列表携带的值',options)
    id=options.id
    //云函数的调用
    wx.cloud.callFunction({
      name:'updateData',
      data:{
        id:id,
        value:20
      }
    })
    .then(res=>{
      console.log('云函数调用成功',res)
    })
    .catch(res=>{
      console.log('云函数调用失败',res)
    })
  }
})

//云函数index.js
// 云函数入口函数
exports.main = async (event, context) => {
  // return event.id+"///"+event.value
  cloud.database().collection('data')
  .doc(event.id)
  .update({
    data:{
      value:event.value
    }
  })
}

39、调用云函数删除数据

// 云函数入口函数
exports.main = async (event, context) => {
  cloud.database().collection('data')
  .doc(event.id)
  .remove()
}

40、请求数据库数据

// 云函数入口函数
wx.cloud.database().collection('num')
	.skip(40)//起始数据开始位置
	.get()
	.then(res=>{
      console.log('云函数调用成功',res)
    })
    .catch(res=>{
      console.log('云函数调用失败',res)
    })
	

41、云函数获取数据库数据

// 云函数入口函数
exports.main = async (event, context) => {
		return await cloud.database().collection('num)
			.skip(event.len)//做分页用
			.limit(event.pageNum)//每页加载多少条数据
			.get()
}
	

42、数据库添加数据

// 云函数入口函数
wx.cloud.database()collection('user').add({
	data:{
		name:name,
		zhanghao:zhanghao,
		mima:mima
	}
})
	

43、微信用户一键登录样式书写

在这里插入图片描述

//me.wxml
<button type="primary" class="btn" open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber"><image class="btn-img" src="/images/weixin.png"></image>微信用户一键登录</button>
//me.wxss
.btn-img{
  height: 30px;
  width: 30px;
  margin-bottom: -18rpx;
}
.btn{
  background: #008c00;
  margin: 200rpx 40rpx 200rpx 40rpx;
}

44、获取用户手机号

//me.wxml
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">获取用户手机号</button>
//me.js
getPhoneNumber(e)
  {
    console.log("用户登录",e)
    if(e.detail.errMsg== "getPhoneNumber:fail user deny"){
      wx.showToast({
        title: '你没有给相关授权',
        icon:'none'
      })
    }
    else{
      wx.cloud.callFunction({
        name:'getPhoneNumber',
        data:{
          weRunData:wx.cloud.CloudID(e.detail.cloudID),
        }
      }).then(res=>{
        console.log(res.result.moblie)
      }).catch(err=>{
        console.error(err)
      })
    }
  },

// 云函数入口函数
exports.main = async (event, context) => {
  var moblie=event.weRunData.data.phoneNumber;
  return{
    moblie
  }
}

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值