微信小程序
01 初步了解
1.1 创建页面
// app.json
{
pages:[
//page目录 / test文件
"pages/test/test" // 添加路径
]
}
1.2 样式导入
/*
app.wxss 全局样式
iphone6实际宽度是750px,听的rpx是750rpx 750rpx === 100vw
1px = 2rpx
字体用px
*/
// 样式导入
// 使用@import语句可以导入外联样式表,@import后跟需要导入的外联样式表的相对路径,用;表示语句结束。
/** common.wxss **/
.small-p {
padding:5px;
}
/** app.wxss 全局样式 **/
@import "common.wxss"; // 导入样式
.middle-p {
padding:15px;
}
1.3 标签
<view></view> <!-- 相当于div -->
<button></button> <!-- 按键 -->
<images></images> <!-- 相当于img -->
<block></block>
1.4 生命周期
// index.js
Page({
data: {
text: 'This is page data.'
},
// 监听页面加载,这里发送请求
onLoad(options) {},
// 监听页面初次渲染完成,用户可以开始操作
onReady() {},
// 监听页面显示
onShow() {},
// 监听隐藏
onHide() {},
// 监听页面卸载,页面跳转或者子页面超过5个被卸载
onUnload() {},
// 页面下拉动作,触发更新
onPullDownRefresh() {},
// oage滚动到底部
onReachBottom() { },
// 用户点击分享
onShareAppMessage() {},
onPageScroll() { },
onResize() {},
onTabItemTap(item) {
}
})
1.5 模块化
导出
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name} !`)
}
//多个
module.exports = {
sayHello
}
exports.sayGoodbye = sayGoodbye //单个
导入
const common = require('common.js')
Page({
helloMINA() {
common.sayHello('MINA')
},
goodbyeMINA() {
common.sayGoodbye('MINA')
}
})
1.6 数据更新
Page({
data:{
msg:123
},
onLoad(){
this.setData({
msg:2222
})
}
})
02 条件语句
2.1 for循环
<view wx:for="{{ arr }}" wx:key="{{ index }}">
{{ index }} <!-- 序号 -->
{{ item }} <!-- 值 -->
</view>
<!-- 修改变量名 -->
<view wx:for="{{ arr }}" wx:for-item="selfItem" wx:for-item="selfIndex">
{{ selfIndex }} <!-- 序号 -->
{{ selfItem }} <!-- 值 -->
</view>
2.2 if语句
<view wx:for="{{ arr }}" wx:key="{{ index }}">
{{ index }} <!-- 序号 -->
{{ item }} <!-- 值 -->
</view>
<!-- 修改变量名 -->
<view wx:for="{{ arr }}" wx:for-item="selfItem" wx:for-item="selfIndex">
{{ selfIndex }} <!-- 序号 -->
{{ selfItem }} <!-- 值 -->
</view>
2.3 block
<!-- 套用层 -->
<block wx:if="{true}"></block>
03 组件
3.1 组件声明周期
created // 组件实例化,但节点树还未导入,因此这时不能用setData
attached // 节点树完成,可以用setData渲染节点,但无法操作节点
ready // (不是onReady) 组件布局完成,这时可以获取节点信息,也可以操作节点
moved // 组件实例被移动到树的另一个位置
detached // 组件实例从节点树中移除
3.2 定义组件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PsvgmK5j-1569935324908)(file:///C:/Users/MACHENIKE/Documents/My Knowledge/temp/877bdad7-b2dd-4329-9d8e-c24d495a9674/128/index_files/4e5aebc7-c36c-43b3-aa6d-d390071e3981.png)]
// headNav.json
{
"component": true,
"usingComponents": {}
}
// headNav.js
// pages/index/index.js
Component({
/**
* 外部传入数值
*/
properties: {
abc:{
type:String, //值类型
value:'', //默认值
observer:'change' //数值改变相应函数
}
},
/**
* 数据
*/
data: {
navArr:[
{ txt: '推荐',url:'/pages/index/index'},
{ txt: '歌单', url: '/pages/menu/menu' },
{ txt: '搜索', url: '/pages/search/search'}
],
nowUrl:''
},
/**
* 组件实例化,但节点树还未导入,因此这时不能用setData
*/
created() {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var nowUrl = currentPage.route //当前页面url
this.setData({ nowUrl })
console.log(this.data.nowUrl);
},
/**
* 组件的方法列表
*/
methods: {
change(){
}
}
})
3.3 父组引入子组
// index.json
{
"usingComponents": {
//headNav组件名
"headNav": "../components/headNav/headNav"
}
}
<!--pages/index/index.wxml-->
<head-Nav></head-Nav>
3.4 子组件方法
<!--pages/index/index.wxml 绑定id -->
<head-Nav id='header_nav'></head-Nav>
// index.js
Page({
//...
testClick(){
//通过获取id 调用下面的方法
this.selectComponent('#header_nav').goWhere(123);
}
})
3.5 子传参数父
//headNav.js
Component({
//....
methods: {
goWhere(e){
/*
发送数据父组件
接收事件名称 parentEvent
接收数据 data
*/
this.triggerEvent('parentEvent, 'sadsadsasd')
}
}
})
<!--
pages/index/index.wxml
bind:name -> parentEvent是接收那个函数的
onParentEvent 父组件中回调数据
-->
<head-Nav bind:parentEvent='onParentEvent'></head-Nav>
// pages/index/index.js
Page({
//...
onParentEvent(e){
console.log('子组件传递父组件');
}
})
3.6 slot
Component({
options: {
multipleSlots: true // 在组件定义时的选项中启用多slot支持
},
properties: { /* ... */ },
methods: { /* ... */ }
})
<!-- 组件模板 -->
<view class="wrapper">
<slot name="before"></slot>
<view>这里是组件的内部细节</view>
<slot name="after"></slot>
</view>
<!-- 引用组件的页面模板 -->
<view>
<component-tag-name>
<!-- 这部分内容将被放置在组件 <slot name="before"> 的位置上 -->
<view slot="before">这里是插入到组件slot name="before"中的内容</view>
<!-- 这部分内容将被放置在组件 <slot name="after"> 的位置上 -->
<view slot="after">这里是插入到组件slot name="after"中的内容</view>
</component-tag-name>
</view>
04 wxs
4.1 标签
<!-- test -- 局部模块name -->
<wxs module="test">
var t = "hello";
function foo(n){
return n*2;
}
moudle.exports = {
t,
foo
}
</wxs>
<text> {{ test.t }} </text>
<text> {{ test.foo(2) }} </text>
4.2 过滤
<wxs module="filter">
function codeTime(time){
var reg = getRegExp("(\d{4})-(\d{2})-(\d{2})(.*)");
return time.replace(reg,"$1/$2/$3");
}
module.exports = {
codeTime:codeTime
}
</wxs>
<text> {{ filter.codeTime('2018-02-03') }} </text>
4.3 脚本
module
list
common.wxs
//common.wxs
function codeTime(time){
var reg = getRegExp("(\d{4})-(\d{2})-(\d{2})(.*)");
return time.replace(reg,"$1/$2/$3");
}
module.exports = {
codeTime:codeTime
}
<!-- 只能使用相对路径 -->
<wxs src='../../list/common.wxs' module='filter' /> <!-- 导入方法 -->
<text> {{ filter.codeTime('2018-02-03') }} </text>
4.4 脚本引用
//test.wxs
function addZore(num){
num *= 1;
return num<10?'0'+num:num;
}
module.exports = {
addZore:addZore
}
//common.wxs
var testModule = require('test.wxs');
function codeTime(time){
var reg = getRegExp("(\d{4})-(\d{2})-(\d{2})(.*)");
return time.replace(reg,"$1/$2/$3");
}
module.exports = {
codeTime,
addZore:testModule.addZore
}
4.5 page绑定wxs
var testModule = require('../../module/test/test.js')
Page(
Object.assign({},testModule)
)
05 事件
5.1 所有事件
touchstart //手指触摸动作开始
touchmove //手指触摸后移动
touchend //手指触摸动作结束
tap //手指触摸后马上离开( 点击 )
touchcancel //手指触摸动作被打断,如来电提醒,弹窗
longpress //手指触摸后,超过350ms再离开,如果指定了事件回调函数并触发了这个事件,tap事件将不被触发
longtap //手指触摸后,超过350ms再离开(推荐使用longpress事件代替)
transitionend //会在 WXSS transition 或 wx.createAnimation 动画结束后触发
animationstart //会在一个 WXSS animation 动画开始时触发
animationiteration //会在一个 WXSS animation 一次迭代结束时触发
animationend //会在一个 WXSS animation 动画完成时触发
touchforcechange //在支持 3D Touch 的 iPhone 设备,重按时会触发
5.2 绑定与冒泡
<view bindtap="handleTap1">事件绑定</view> <!-- bind -->
<view catchtap="handleTap1">阻止冒泡</view> <!-- catch -->
/*
changedTouches 手指的数组
changedTouches -> dataset 绑定在组件上的data属性
currentTarget 当前绑定事件的方法
detai 触发事件的位置
target 实际从哪个数组触发的事件(用于事件委托)
type 触发的事件类型
*/
5.3 网络请求
wx.request({ url,success,fail,complete })
06 页面跳转
//complete 成功失败回调
wx.navigateTo({url,success,fail,complete}) // 关闭当前页,打开子页面,不超过5个
wx.redirectTo({url,success,fail,complete}) // 新开页面
wx.switchTab({url,success,fail,complete}) //跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面
wx.reLaunch({url,success,fail,complete}) //关闭所有页面,打开到应用内的某个页面
//返回的页面数,如果 delta 大于现有页面数,则返回到首页。 number
wx.navigateBack({delta,success,fail,complete}) //关闭当前页面,返回上一页面或多级页面
07 导航
7.1 导航栏设置
//app.json
{
"pages":[
"pages/home/list"
],
"window":{
}
}
window
/*
navigationBarBackgroundColor 导航栏背景颜色
navigationBarTextStyle 导航栏标题颜色 black / white
navigationBarTitleText 导航栏标题文字内容
backgroundColor 窗口的背景色
backgroundTextStyle 下拉 loading 的样式 dark / light
navigationStyle 导航栏样式,仅支持以下值:default 默认样式custom 自定义导航栏,只保留右上角胶囊按钮。
enablePullDownRefresh 是否开启全局的下拉刷新。
onReachBottomDistance 页面上拉触底事件触发时距页面底部距离,单位为px
pageOrientation 屏幕旋转设置 auto / portrait / landscape
backgroundColorTop 顶部窗口的背景色,仅 iOS 支持
backgroundColorBottom 底部窗口的背景色,仅 iOS 支持
*/
7.2 导航组件
<!-- url 跳转地址 -->
<navigator url="/pages/home/list?abc=22"></navigator>
08 App
8.1 全局参数
//App.js
App({
data:{a:1},
onLaunch(option){
// option 场景值
}
})
//其他页面
const app = getApp();
Page({
onLoad(){
console.log(app)
}
})
8.2 获取page地址
var pages = getCurrentPages() // 获取加载的页面
var currentPage = pages[pages.length-1] // 获取当前页面的对象
var url = currentPage.route // 当前页面url