原生微信小程序学习基础语法(一)

119 阅读5分钟

第一部分:基础学习

1、删除app.js以下部分,将版本更换为webwife

"renderer": "skyline",
 // "rendererOptions": {
//   "skyline": {
//     "defaultDisplayBlock": true,
//     "defaultContentBox": true,
//     "tagNameStyleIsolation": "legacy",
//     "disableABTest": true,
//     "sdkVersionBegin": "3.0.0",
//     "sdkVersionEnd": "15.255.255"
//   }
// },
// "componentFramework": "glass-easel",

2、app.json的学习

1、主页面的设置

在app.json中放在第一位 或 使用"entryPagePath": "pages/list/list"

2、windeow,属性多去查找文档

  "window": {
    "navigationBarTitleText": "一起向前",//顶部栏名称
    "navigationBarBackgroundColor": "#f3514f",//顶部栏颜色
    "enablePullDownRefresh": true,//是否开启下拉刷新
    "backgroundColor": "#efefef",//下拉的背景颜色
    "backgroundTextStyle": "dark"//下拉的状态
  },

3、tabBar导航栏的设置

  "tabBar": {
    "selectedColor": "#f3514f",激活的文字颜色
    "color": "##047DDA",未激活的文字颜色
    "backgroundColor": "#efefef",背景颜色
    "borderStyle": "white",边缘线的颜色
    "position": "top",导航栏的位置
    "list": [{
      "text": "首页",
      "pagePath": "pages/index/index",
      "iconPath": "",
      "selectedIconPath": ""
    },{
      "text": "分类",
      "pagePath": "pages/list/list",
      "iconPath": "",
      "selectedIconPath": ""
    },{
      "text": "购物车",
      "pagePath": "pages/cart/cart",
      "iconPath": "",
      "selectedIconPath": ""
    },{
      "text": "我的",
      "pagePath": "pages/profile/profile",
      "iconPath": "",
      "selectedIconPath": ""
    }
  ]
  },

4、 "sitemapLocation": "sitemap.json",小程序的是否被索引的配置文件的存放位置,如果没有默认允许。

3、小程序组件的学习

1、宽度自适应问题: 所有的机型都是750rpx宽度,自适应设置 :width: 375rpx;

2、组件使用

<text user-select space="nbsp"> 尚           硅    谷</text>
  设置是否长按可选   设置空格是否可见 
<image src="/assge/banner/banner-1.png" 
mode="aspectFit" show-menu-by-longpress lazy-load />
缩放方式              长按是否可以分享     加载
<swiper 
autoplay  自动播放
circular  连续循环
interval= "2000" 播放时间
indicator-dots   小黑点
indicator-color="#E9BF5D"  小黑点颜色
indicator-active-color="#3A3A3A"
>

3、navigator跳转链接

<navigator url="/pages/list/list" open-type="switchTab">到商品列表</navigator>
<navigator url="/pages/cate/cate" open-type="navigate">到分类列表</navigator>
<navigator url="/pages/cate/cate" open-type="redirect">redirect会关闭上级标志</navigator>

image.png

4、scroll组件

<scroll-view class="scroll-x" scroll-x>
  <view>1</view>
  <view>2</view>
  <view>3</view>
</scroll-view>

5、矢量图标库

建议在阿里选择要使用的图标 image.png 然后倒入公共样式文件app.wxss image.png

6、背景图片设置,不能用本地地址,要用网络地址

.bg-image{
  height: 400rpx;
  background-image: url(https://ts1.cn.mm.bing.net/th/id/R-C.9b72bb603cc9d943a01f4e603cfb4727?rik=mNFGKWaXS%2fYm%2bQ&riu=http%3a%2f%2fn.sinaimg.cn%2fsinakd20220115ac%2f586%2fw1919h1067%2f20220115%2f3d4e-7d0ceeca40adf3311f7d0caaa5b90d8b.jpg&ehk=8BMT4PIGhUmihBJ52PJEvQGaRrnSq0W%2bMw6Jqm2EzRk%3d&risl=&pid=ImgRaw&r=0);
}

4、事件系统

1、事件绑定

<!-- 第一种绑定事件的方法 -->
<button type="primary" size="mini" bind:tap="handler">绑定事件</button>
<!-- 第二种绑定事件的方法 -->
<button type="warn" size="mini" bindtap="handler">绑定事件</button>

<input type="text" bindinput="grtI"/>
Page({
  handler(e){
    console.log(e)
  },
  grtI(e){
    console.log(e.detail.value)
  }
})

image.png

2、事件冒泡,catch:tap可以阻止子元素事件冒泡

<view class="catch" bind:tap="paR">
<!-- catch:tap可以阻止事件冒泡 -->
<button catch:tap="btnH">按钮</button>
</view>

3、事件传参

//第一种
<view class="view11">
<!-- 如果需要进行事件传参,需要使用自定义属性 -->
<button bind:tap="btnHH" data-id="2" data-name="tom">按钮</button>
<button bind:tap="btnH11" mark:id="33" mark:name="you">mark</button>
</view>
console.log(e.target.dataset);
//第二种
  btnH11(e){
    console.log(e.mark.id);
    console.log(e.mark.name);
  }

5、wxml语法

1、声明和绑定

//wxml
<view>{{ school }}</view>
<view>{{ obj.name }}</view>
<view id="{{ id }}">绑定属性值</view>
<checkbox checked="{{ isC }}"/>
<view>{{id+2}}</view><view>{{id-2}}</view>
<view>{{id>=2}}</view><view>{{id === 3 ? '等于' : '不等于'}}</view>
//js
  data:{
    school:'尚硅谷',
    obj:{
      name:'tom'
    },
    id: 3,
    isC: true
  }

2、对象类型setData()修改数据,更新数据,更新视图,删除单个/多个属性

//wxml
<view style="text-align: center; border: 2px solid aqua;">{{ num }}</view>
<button bind:tap="upd" size="mini" type="primary">更新num</button>
<button bind:tap="upd22" size="mini" type="warn">更新num</button>
<view>{{ userInfo.name }}和{{ userInfo.age }}</view>
<button type="warn" size="mini" bind:tap="updUser">修改对象类型数据</button>
<view class="line"></view>
//js
  upd(){
    console.log(this.data.num);
    this.setData({
      //key需要更新的数据,value最新的值
      num: this.data.num + 1
    })
  },
  upd22(){
    this.setData({
      num: this.data.num - 1
    })
  },
  updUser(){
    //新增属性 3种方法
    // this.setData({
    //   //没有则新增,有则修改
    //   'userInfo.name': 'lser',
    //   'userInfo.age': 10
    // })
  //   const userInfo = {
  //     ...this.data.userInfo,
  //     name: 'jerry',
  //     age: 3333
  //   }
  //   this.setData({
  //     userInfo
  //   })
  // const userInfo = Object.assign(this.data.userInfo,{name: 'jerry'},{age: 444})
  // this.setData({
  //   userInfo
  // })
  // //删除单个属性
  //   delete this.data.userInfo.age
  //   this.setData({
  //     userInfo: this.data.userInfo
  //   })
  //删除多个属性  ...rest剩余元素
  const {age,name, ...rest} = this.data.userInfo
  this.setData({
    userInfo: rest
  })
}

3、数组类型setData()修改更新 【使用时位路径要用引号包裹】

//wxml
<view wx:for="{{ list }}" wx:key="index">{{ item }}</view>
<button size="mini" type="primary" bind:tap="updArr">修改数组类型</button>
//js
  updArr(){
    // // 新增
    // this.data.list.push(4)
    // this.setData({
    //   list: this.data.list
    // })
    // //修改
    // this.setData({
    //   'list[0]' : 6
    // })
    //删除
    this.setData({
      list : this.data.list.splice(1)
    })
  }

4、简易的双向数据绑定 给对应的属性添加model:

<input type="text" model:value="{{ value }}"  />
<checkbox model:checked="{{ isC }}" />同意协议
//页面的变化,数据也会变化,双向绑定

5、列表渲染

<view wx:for="{{ numList }}" wx:key="*this">{{ item }} - {{ index }}</view>
<!-- 渲染数组时item为数组值,index为数组下标 -->
<view wx:for="{{ obj }}">{{ item }} - {{ index }}</view>
<!-- 渲染对象时item为value,index为key -->
<view wx:for="{{fruitList }}" wx:key="id">{{ item.name }} </view>

<view class="line"></view>
<view wx:for="{{fruitList}}" wx:key="id">
{{item.name}}
</view>
<view wx:for="{{ obj }}" wx:key="index">
{{ item }} - {{ index }}
</view>
<view wx:for="{{ fruitList }}" wx:key="id">
<view>名字:{{item.name}}</view>
<view>价格:{{item.id}}</view>
</view>

6、条件渲染 if后成立则展示,

<!-- wx:if  wx:elif  wx:else 结合使用,使用时中间不能被打断 -->
<view wx:if="{{num === 1}}">num等于 {{ num }}</view>
<view wx:elif="{{num === 2}}">num第二个等于 {{ num }}</view>
<view wx:else>num大于2,目前num等于 {{ num }}</view>
<view hidden="{{!ifS}}">当ifS是ture时展示结构,</view>
<button type="primary" size="mini" bind:tap="upjia">num加一</button>
<button type="warn" size="mini" bind:tap="upjian">num减一</button>

一、生命周期

1、应用生命周期函数

App{(
  onLaunch: function () {
    console.log('onLaunch 当小程序初始化完成时');
  },
  onShow: function (options) {
    console.log('onShow 当小程序启动,或从后台进入前台显示');
  },
  onHide: function () {
    console.log('onHide 当小程序从前台进入后台,会触发 onHide');
  },
  )}

2、页面生命周期函数

Page({
  /**
   * 页面的初始数据
   */
  data: {},
  onLoad(options) {
    console.log('onLoad 页面创建时执行');
  },
  onReady() {
    console.log('onReady 页面初次渲染成功,可以与视图层进行交互');
  },
  onShow() {
    console.log('onShow 页面在前台展示的时候');
  },
  onHide() {
    console.log('onHide 当前页面被隐藏时触发');
  },
  onUnload() {
    console.log('onHide 当前页面卸载时触发');
  },

二、微信API的使用

1、wx.request()接口API

  wx.request({
    url:'https://jsonplaceholder.typicode.com/posts/1',
    method: 'GET',
    data:{

    },
    header:{

    },
    success:(res) => {
      console.log(res)
    },
    fail:(err) => {
      console.log(err)
    },
    //不论成功还是失败都会调用
    complete:() => {
      console.log(res);
    }
  })

2、loading提示框

getData(){
  //显示提示框
  wx.showLoading({
    title: '数据正在加载......',
    //是否展示透明图层,防止触碰
    mask: true,
  })

  wx.request({
    url:'https://jsonplaceholder.typicode.com/posts/1',
    method: 'GET',
    //不论成功还是失败都会调用
    complete:() => {
      wx.hideLoading()
    }
  })
}

3、消息提示框

async delHandler(){
const  res = await wx.showModal({
  content: '是否删除该商品',
  title: '提示'
})
if(confirm){
  wx.showToast({
    title: '删除成功',
    icon: 'none',
    duration: 2000
  })
}else{
  wx.showToast({
    title: '取消删除',
    icon:'error',
    duration:2000
  })
}
}

4、本地存储API

  //存储
setS(){
//   wx.setStorageSync('num', 121)
//   wx.setStorageSync('obj', {name: 'tom',age: '19'})
  wx.setStorage({
    key: 'num',
    data: 1
  })
  wx.setStorage({
    key: 'obj',
    data: {name:'jurry',age:'20'}
  })
},
//获取
async getS(){
//  const num = wx.getStorageSync('num')
//  const obj = wx.getStorageSync('obj')
  const {data} = await wx.getStorage({
    key: 'obj'
  })
 console.log(data);
},
//删除
remS(){
  // wx.removeStorageSync('num')
  wx.removeStorage({
    key: 'obj'
  })
},
//清空
cleS(){
  // wx.clearStorageSync()
  wx.clearStorage()
},

5、路由和通讯

  navigateTo(){
    //保留当前页面,跳转到其他页面,不能跳转tabBar页面
    wx.navigateTo({
      url: '/pages/cate/cate',
    })
  },
  redirectTo(){
    //销毁当前页面,跳转到应用其他页面,不能跳转tabBar页面
    wx.redirectTo({
      url: '/pages/cate/cate',
    })
  },
  switchTab(){
    //跳转到tabBar页面,不能跳转非tabBar页面,不能携带参数
    wx.switchTab({
      url: '/pages/cart/cart', 
    })
  },
  reLaunch(){
    //关闭所有页面,然后跳转某一个页面
    wx.reLaunch({
      url: '/pages/list/list?id=2&name=tom',
    })
  },
  navigateBack(){
    //默认返回上一级,delta: n 返回第N级
    wx.navigateTo()
  },

6、上拉加载

//json
{
  "usingComponents": {},
  "onReachBottomDistance": 50
}
//js
Page({
  data:{
    numList:[1,2,3]
  },
  onReachBottom(){
    //监听用户上拉加载更多
    wx.showLoading({
      title: '数据加载中。。。',
    })
    setTimeout(()=>{
    const lastnum = this.data.numList[this.data.numList.length - 1]
    const newArr = [lastnum + 1,lastnum + 2,lastnum + 3]
    this.setData({
      numList: [...this.data.numList, ...newArr]
    })
    wx.hideLoading()
    },1500)
  }
})

7、下拉刷新

//json
{
  "usingComponents": {},
  "onReachBottomDistance": 50,
  "enablePullDownRefresh": true,
  "backgroundColor": "#efefef",
  "backgroundTextStyle":"dark"
}
//js
  onPullDownRefresh(){
    //监听用户下拉刷新
    this.setData({
      numList: [1,2,3]
    })
    //在下拉刷新以后,loading效果有可能不会回弹回去
    if(this.data.numList.length === 3){
      wx.stopPullDownRefresh()
    }
  }

三、自定义组件

1、组件的创建

1、先创建文件夹components
2、注册在app.json中,子组件则定义在子组件json文件中
  "usingComponents": {
    "custom-checkbox":"/components/custom-checkbox/custom-checkbox"
  }
3、直接<custom-checkbox />使用就可以了

2、properties属性的使用