ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

微信小程序 - 基本语法

2021-02-16 15:36:00  阅读:182  来源: 互联网

标签:console 微信 页面 程序 语法 res font data wx


微信小程序基础知识

1.定时器setTimeout()

本案例:待页面加载完成后,3秒后将setTineout()函数中的courseItems数据渲染到页面上

注释: ①=>函数 this调用的时外部的对象

​ ②function() this调用的是函数本身

data:{
	courseItems:[]
}

onReady:生命周期函数--监听页面初次渲染完成

onReady: function () {
    console.log("页面第一次渲染完成")
    setTimeout( ()=> {
      console.log("3秒钟到了")
      
      //向courseItems数组中添加元素
      this.data.courseItems.push({
        id:"1",
        courseImg:"/assets/image/2036271.jpg",
        courseTitle:"java",
        courseTeacher:"风亚非",
        courseStudynum :1000,
        isStar:false,
        score:90
      })
      
      // this.setData()  把push到courseItems数组里面的元素渲染到页面上
      this.setData({
        courseItems:this.data.courseItems
      })
    },3000)
  },

2.事件绑定

  • bind、catch、capture-bind、capture-catch、mut-bind

    1.普通绑定(事件会冒泡) bind

    2.绑定并阻止事件冒泡 catch

    3.捕获的顺序与冒泡相反 capture-bind

    4.中断捕获阶段和取消冒泡阶段 capture-catch

    5.互斥事件绑定 mut-bind

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

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

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

下图为冒泡事件

冒泡事件

  • 事件对象

    当组件触发事件时,逻辑层绑定该事件的处理函数会收到一个事件对象BaseEvent

3.组件操作

1向组件中传值

自定义的组件 x-beauty
wxml代码:
<view class="teacherItem">
			  //teacherItem.teacherImg为data里面的teacherImg
  <image src="{{teacherItem.teacherImg}}" mode="aspectFill"/>
  			  //teacherItem.teacherName为data里面的teacherImg
  <view>{{teacherItem.teacherName}}</view>
</view>

wxjs代码:
  properties: {
    teacherItem:Object
  },
页面代码
wxml代码:
<view class="teacher-container">
  <block wx:for="{{teacherItems}}" wx:key="id">
    <x-beauty teacherItem="{{item}}"/>  自定义一个teacherItem变量
  </block>
</view>

wxjson代码:
{
	//引用组件
  "usingComponents": {"x-beauty":"/component/x-beauty/x-beauty"}
}

wxjs代码:
data: {
    teacherItems:[
      {
        id:1,
        teacherImg:"/assets/image/2036271.jpg",
        teacherName:"翟立普"
      },
      {
        id:2,
        teacherImg:"/assets/image/2036271.jpg",
        teacherName:"封亚非"
      },
      {
        id:3,
        teacherImg:"/assets/image/2036271.jpg",
        teacherName:"陈浩楠"
      }
    ]
  },

2.在组件内部绑定图片抖动事件

wxss代码:

/*抖动引用到deleteItem对象*/
.deleteItem{
  animation:shak 1s 0s infinite;
}

/*定义关键帧动画*/
@keyframes shak{
  0%{
    transform:rotate(0deg)
  }
  10%,20%,30%{
    transform:rotate(-4deg)
  }
  15%,25%,35%{
    transform:rotate(4deg);
  }
  40%{
    transform:rotate(-2deg);
  }
  45%{
    transform:rotate(2deg);
  }
  50%{
    transform:rotate(0deg);
  }
  100%{
    transform:rotate(0deg);
  }
wxjs代码:
/*
	在data里面设置isDelete的值
*/
Component{
	data: {
    isDelete:false
  },
}

wxml代码:
/*
  为图片绑定抖动事件  
  判断isDelete是否为true,为true,执行deleteItem并抖动
*/
<view class="teacherItem {{isDelete?'deleteItem':''}}">
  <image src="{{teacherItem.teacherImg}}" mode="aspectFill"/>
  <view>{{teacherItem.teacherName}}</view>
</view>

3.在组件中设置删除图标

wxml代码:
<view class="teacherItem {{isDelete?'deleteItem':''}}" bindlongpress="_deleteItem">
  <image src="{{teacherItem.teacherImg}}" mode="aspectFill"/>
  <view>{{teacherItem.teacherName}}</view>
  /*设置删除图标X*/
  <view class="delBtn" hidden="{{!isDelete}}" bindtap="handerDelete">X</view>
</view>
.teacherItem{
	position:relative; //固定X的位置
}
.delBtn{
  position:absolute;  //固定X的位置
  top:-6px;
  right:-6px;
  background-color: red;
  width: 20px;
  height: 20px;
  text-align:center;
  line-height: 20px;
  border-radius: 10px;
}

4.获取事件中的参数

wxml代码:
//通过组件
//方法二
<view bindtap="handTap">
  <x-course id="1" data-title="第一个课程" />
  <x-course id="2" data-title="第二个课程" />
  <x-course id="3" data-title="第三个课程" />
  <x-course id="4" data-title="第四个课程"/>
</view>

//方法一
 <x-course id="1" data-title="第一个课程" bindtap="handTap"/>
 <x-course id="2" data-title="第二个课程" bindtap="handTap"/>
 <x-course id="3" data-title="第三个课程" bindtap="handTap"/>
 <x-course id="4" data-title="第四个课程" bindtap="handTap"/>
wxjs代码:
Page({
  handTap:function (evt) {
  	//方法一
    console.log("课程条目id:",evt.currentTarget.id,evt.currentTarget.dataset.title)
    //方法二:
    console.log("课程条目id:",evt.target.id,evt.target.dataset.title)
  },
 )}

5.模板使用

<template name="itlike">
  <view class="test">
    <view>{{title}}</view>
    <view>详情</view>
    <view>介绍</view>
  </view>

</template>

<template is="itlike" data="{{title:'拉拉',name:'哈哈'}}"></template>

6.WXS基本语法

方式一:
在wxml里面写WXS模块
<wxs module="tool">
  function tst(){
    console.log("xxx-test")
    return "xxx-test"
  }
  module.exports = {
    tstFunc:tst
  }
</wxs>

调用: 模块.方法
<text>{{tool.tstFunc()}}</text>
方式二:
在该目录下新建一个tool.wxs文件
tool.wxs代码:
function sum(num1,num2){
  return num1+num2
}
module.exports = {
  sumFunc:sum
}

<!-- 引入模块 -->
<wxs module="tool" src="tool.wxs"></wxs>

<text>{{tool.sumFunc(6,8)}}</text>

7.flex布局

display:block;  变成块级标签
display:inline-block;  变成行级块级标签

8.icon

<block wx:for="{{iconArr}}" wx:key="*this">  <!-- *this代表本身的属性  消除下面的警告 -->
  <icon type="{{item}}" size="{{(index+1) * 10 + 'rpx'}}" color="yellow"></icon>
</block>

 data: {
    iconArr:["success", "success_no_circle", "info", "warn", "waiting", "cancel", "download", "search", "clear"]
  },

9.通过iconfont获取图片路径(远程路径)

第一步:在iconfont中选择需要的图片加入购物车

第二步:添加至项目,在Font class中生成链接 ,向网页发送htttps:// + 链接

第三步:将生成的代码复制到app.wxss中

第四步:在iconfont的资源管理中找到我发起的项目中的Unicode,用其中的代码替换掉app.wxss中的@font-face代码

@font-face {
  font-family: 'iconfont';  /* project id 2341311 */
  src: url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.eot');
  src: url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.eot?#iefix') format('embedded-opentype'),
  url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.woff2') format('woff2'),
  url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.woff') format('woff'),
  url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.ttf') format('truetype'),
  url('//at.alicdn.com/t/font_2341311_f2k8ah97clh.svg#iconfont') format('svg');
}

.iconfont {
  font-family: "iconfont" !important;
  color: red;
  font-size: 36rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-account:before {  /*伪元素选择器*/
  content: "\e655";
}

.icon-password:before {
  content: "\e734";
}

第五步:在wxml中引用app.wxss中的图标

<text class="iconfont icon-account"></text>
<text class="iconfont icon-password"></text>

第六步:我们可以在.iconfont中修改图标的属性

.iconfont {
  font-family: "iconfont" !important;
  color: red;
  font-size: 36rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

10.checkbox绑定事件的使用

chexbox组件想要使用bindchange事件,需要在chexbox中定义一个value属性

案例:当isRemberPaword = true的时候,checked可以选中
<checkbox-group bindchange="RemberPassword">
          <checkbox value="1" checked="{{isRemberPaword}}">记住密码</checkbox>
</checkbox-group>
RemberPassword:function(evt){
    let val = evt.detail.value.length
    this.setData({
    isRemberPaword:val == 1
    })
  },
  
data{
	isRemberPaword:false
},

11.页面跳转和传值

wx.navigateTo 和 wx.redirectTo

跳转到指定页面并传值id=6
navigateTo  只能跳转非tabpBar页面
wx.navigateTo({
     url: "/pages/buttonDemo/buttonDemo?id=6",
  })
关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面
wx.redirectTo({
    url: "/pages/swiper/swiper",
  })

12.movable滑动组件

13.自定义组件

14.生命周期

微信小程序+云开发

1.初始化项目

①安装node.js

②在外部终端中安装Vant Weapp组件 npm i @vant/weapp -S --production

③在小程序工具中选择构建npm工具

④打开详情,使用npm模块

2.我的第一个云函数

在cloudFunctions创建一个node.js函数add
在add下的index.js中写云函数
之后点击上传并部署

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
	env:"环境ID"
})

// 云函数入口函数
exports.main = async (event, context) => {
  let a = event.a;
  let b = event.b;
  return a+b
}

在页面中调用,并把结果返回到页面上

<button bindtap="summation">云函数加法</button>
<text>{{result}}</text>

Page({
  data:{
    result:''
  },
  summation(){
    wx.cloud.callFunction({
      name:"add",
      data:{
        a:1,
        b:3
      },
      success:(res)=>{
        console.log("请求成功",res)
        this.setData({
          result:res.result
        })
      },fail(err){
        console.log("请求失败",err)
      }
    })
  }
})

3.获取小程序用户的openid

// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}
<button bindtap="getopenid">获取用户openid</button>

//获取用户openid

 getopenid(){

  wx.cloud.callFunction({

   name:"getopenid",

   success(res){

​    console.log("获取成功",res.result.openid)

   },fail(err){

​    console.log("获取失败",err)

   }

  })

 }


4.上传图片到云存储,并展示

<button bindtap="upload">上传文件</button>

wx.chooseImage:选择图片

wx.cloud.uploadFile:上传文件到云存储

Page({
	data:{
		imgurl:""
	},
  //上传文件
  upload(){
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success (res) {
        console.log("选择成功",res)
        that.uploadImg(res.tempFilePaths[0]);
      }
    })
  },
  uploadImg(fileUrl){
    wx.cloud.uploadFile({
      cloudPath: new Data().getTime()+'.png',//用时间戳来表示每个图片的名字
      filePath: fileUrl, // 小程序临时文件路径
      success: res => {
        // 返回文件 ID
        console.log("上传成功",res)
        
        //想data数组里面传值
        this.setData({
          imgurl:res.fileID
        })
      },
      fail: console.error
    })
  }
})

5.选择视频文件

wx.chooseVideo

6.上传excel文件到云存储

7.下载文件

wx.cloud.downloadFile   下载数据库里面的文件
wx.openDocument			打开

标签:console,微信,页面,程序,语法,res,font,data,wx
来源: https://www.cnblogs.com/zhailipu/p/14406734.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有