search
HomeWeb Front-endJS TutorialQuick knowledge about WeChat mini program

Quick knowledge about WeChat mini program

Feb 28, 2018 pm 02:47 PM
AppletsKnowledgequick check

This article mainly shares with you the quick knowledge of WeChat mini programs, which can make it easier for everyone to develop WeChat mini programs. I hope this article can help everyone.

1. Configuration

Full configuration analysis

  • ##project.config.json (project configuration file)

{
    // 文件描述
    "description": "项目配置文件",
    // 项目代码配置
    "setting": {
        // 是否检查 url 域名安全性和 TLS 版本
        "urlCheck": false,
        // 是否将项目的 es5 代码转成 es6
        "es6": true,
        // 是否自动补全 css 兼容前缀
        "postcss": true,
        // 是否压缩代码
        "minified": true,
        // 是否启用新功能
        "newFeature": true
    },
    // 编译方式
    "compileType": "miniprogram",
    // 版本号
    "libVersion": "1.7.2",
    // appid
    "appid": "touristappid",
    // 项目名
    "projectname": "haiyangbg",
    // 项目配置
    "condition": {
        // 搜索关键字
        "search": {
            "current": -1,
            "list": []
        },
        // 客服
        "conversation": {
            "current": -1,
            "list": []
        },
        // 编译方式
        "miniprogram": {
            "current": -1,
            "list": []
        }
    }
}
  • app.json (mini-program configuration)

{
  // 项目路由设置(第一项为首页)
  "pages":[
    "pages/index/index",
    "pages/logs/logs"
  ],
  // 窗口设置
  "window":{
    // 顶部导航栏背景色,必须是十六进制颜色值,如"#000000"
    "navigationBarBackgroundColor": "#9ef468",
    // 顶部导航栏显示文字
    "navigationBarTitleText": "组件展示",
    // 导航栏文字颜色,仅支持 black/white
    "navigationBarTextStyle": "black",
    // 下拉背景的文字样式,仅支持 dark/light
    "backgroundTextStyle":"light",
    // 下拉背景色,必须是十六进制颜色值,如"#000000"
    "backgroundColor": "#333",
    // 是否开启下拉刷新
    "enablePullDownRefresh": true,
    // 距离最底端触多少距离时触发触底事件,单位px
    "onReachBottomDistance": 40
  },
  //网络请求过期时间,单位毫秒
  "networkTimeout": {
    // 普通ajax请求
    "request": 20000,
    // Socket请求
    "connectSocket": 20000,
    // 文件上传
    "uploadFile": 20000,
    // 文件下载
    "downloadFile": 20000
  },
  // tab导航栏
  "tabBar": {
    // 文字的颜色
    "color": "#999",
    // 选中时文字的颜色
    "selectedColor": "#000",
    // 背景色
    "backgroundColor": "#fff",
    // 上边框的颜色,仅支持 black/white
    "borderStyle": "black",
    // tab导航栏显示在底部还是顶部(顶部不显示图片)
    "position": "bottom",
    // 导航栏列表项
    "list": [{
      // 导航到的页面路径
      "pagePath": "pages/index/index",
      // tab按钮上的文字
      "text": "组件",
      // 图片路径
      "iconPath": "img/com-l.png",
      // 选中后显示的图片
      "selectedIconPath": "img/com-d.png"
    },{
      "pagePath": "pages/logs/logs",
      "text": "API",
      "iconPath": "img/api-l.png",
      "selectedIconPath": "img/api-d.png"
    }]
  },
  // 调试信息
  "debug": true
}
  • page.json (single Page configuration)

The

json of a single page is the window field of app.json, when loaded into this page When #onLaunch ------ Triggered when the mini program initialization is completed (will only be called once)

onShow ------ 1. Mini program starts 2. Enter the foreground display from the background, trigger

  • onHide ------ When the applet enters the background from the foreground, trigger

  • onError -- ---- 1. A script error occurred 2. The api call failed and was triggered with an error message

  • Single page Page life cycle

  • onLoad ------ Triggered when the page is loaded (will only be called once)

onShow ------ When the page is displayed, Trigger
  • onReady ------ When the initial rendering is completed, trigger (will only be called once)

  • onHide ----- - When the page is hidden, trigger

  • onUnload ------ When the page is unloaded, trigger

  • Details Life cycle classification:
  • 1. Mini program launch:
  • App.onLaunch

    - ->
  • App.onShow
- -> ; Register pages in app.json pages (in index order) - -> Set app routing as homepage routing - -> Deep copy homepage page parameters - -> Initialize homepage data - ->
Page. onLoad

- -> Page.onShow - ->

Page.onReady

2. Switch to the background (app and page life cycles overlap ): The applet was switched to the background - -> page.onHide - -> App.onHide - -> Switched back to the applet Program - -> App.onShow - ->

page.onShow

3. Jump page:

old represents the previous page , new means new pagenavigateToJump- -> Set the route as the target page route- -> old.onHide - -> Initialization page data - ->

new.onLoad

- ->

new.onShow

- ->

new.onReady
  1. redirectToRedirect- -> Set routing- -> old.onUnload - -> init data - -> new .onLoad - -> new.onShow - ->

    new.onReady
  2. ##navigateBack Page return - -> Set routing - -> old.onUnload - -> init data - -> new.onShow

    ##reLaunch
  3. Restart- -> Set routing- ->
  4. old.onUnload

    - -> init data - -> new.onLoad - -> new.onShow - -> new.onReady

  5. ##switchTabTab switch (picture taken from Official document)3. Data binding and rendering

  6. Data Binding: { { message } }

  7. Rendering

Quick knowledge about WeChat mini program##List rendering:

- wx:for=" { { message } } "  
- wx:for-index="idx" (设置索引的变量名,默认 index ) 
- wx:for-item="itemName"(设置每一项的变量名,默认item )

Rendering block:
  1. Conditional rendering:
  2. - wx:if="boolean" - wx:elif="boolean" -wx:else="boolean" == (if - else if - if)
    - hidden="boolean"
  3. 4. Template )
  • Basic usage:

  • (Define code snippets, which can be called in different places, use the name attribute as the name of the template, and use the is attribute when calling)

    // 源码(需要和调用的页面在同一个wxml里)
    <template>
      <view>
        I am {{ name }} 
      </view>
    </template>
    
    // 调用
    <template></template>
    
    // js 数据
    Page({
      data: {
        message: {
          name: '海洋饼干'
        }
      }
    })
  • Advanced usage
  • When many pages needed the same template, the template needed to be imported

First Create a new

template folder

in the pages folder, and create a new template.wxml file in the folder

// template.wxml
<template>
  <view>
    I am {{ name }} 
  </view>
</template>
// page.wxml 调用
<import></import>
<template></template>

// js 数据
Page({
  data: {
    message: {
      name: '海洋饼干'
    }
  }
})

5. Event

Event list

Click Event

Click eventtap

Long press event (more than 0.35 seconds)
    longpress
  1. ##Touch
    event
  • touch start
  • touchstart
  • Start moving after touching
  • touchmove
  • Interrupted after touch

    touchcancel
    • Touch ended touchend

    • Animation
    • Event
      • 过渡完成时触发 transitionend

      • 动画开始时触发 animationstart

      • 一次迭代结束时触发 animationiteration

      • 动画完成时触发 animationend

      事件冒泡,事件捕获

    1. 绑定事件 + 冒泡:bind + 事件名  , 如 bindtap

    2. 绑定事件 + 阻止冒泡:catch + 事件名 , 如 catchtap


    1. 捕获 + 冒泡:capture-bind: + 事件名  , 如 capture-bind:tap

    2. 捕获 + 中断事件 + 取消冒泡:capture-catch: + 事件名  , 如 capture-catch:tap

    事件对象

    • BaseEvent( 基础事件,所有事件的父类 )

      • 同 target

      • id ( String - 事件源的id )

      • tagName ( String - 当前组件的类型 )

      • dataset ( Object - 事件源组件上由data-开头的自定义属性集合 )

      • type ( String - 事件类型 )

      • timeStamp ( Integer - 事件生成时的时间戳 )

      • target ( Object - 触发事件的组件的属性 )

      • currentTarget ( Object - 当前组件的属性 )

    • TouchEvent ( 触摸事件 )

      • identifier ( Number - 触摸点的标识符 )

      • pageX ( Number - 距文档左上角 x 轴的距离 )

      • pageY ( Number 距文档左上角 y 轴的距离 )

      • clientX ( Number 距页面可显示区域 x 轴的距离 )

      • clientY ( Number 距页面可显示区域 y 轴的距离 )

      • touches ( Array 停留在屏幕中的触摸点的信息对象集合 )

      • changedTouches ( Array 变化的触摸点信息对象集合 )

    • CustomEvent ( 自定义事件 )

      • detail ( Object - 自定义事件额外的信息 )

    6. wxs 模块

    wxs 文件就是 js 文件,引入 wxs 文件就是引入一个 js 模块( 不能用es6 ),现有两种引入方式

    1. wxml 里引用,使用 <wxs></wxs> 标签
        1.1. module 必填,为当前模块的模块名
        1.2. src 选填,引用 .wxs 文件的相对路径(仅当标签为 单闭合标签 标签的内容为空 时有效)
        1.3. 例

         引入:<wxs></wxs>
      
         自己撸:
         <wxs>
             var foo = '海洋饼干'
             module.exports = {
                 foo
             }
         </wxs>
    2. wxs 里引用,使用 require 引用
        2.1. 例 var tools = require("./tools.wxs")

    7. wxss 样式

    微信版的 css ,几个不同的地方

    1. 添加 自适应尺寸单位 ( rpx )

    2. 添加 导入外联样式 ( @import )

    3. 精减 css选择器,只支持

      1. 类选择器 .class

      2. id选择器 #id

      3. 标签选择器 element

      4. 兄弟选择器 element1,element2

      5. 伪元素选择器 只支持两种 ::after ::before

    8. 自定义组件

    使用自定义组件

    1. 创建自定义组件( 类似于page,但需要在 json 文件中将 component 字段设为 true

      {
        "component": true
      }
    2. 创建组件构造器 ( 构造函数不是page(),而是Component() )

      Component({
        // 组件的对外属性(父组件传的数据)
        properties: {
          msg: {
            type: String,
            value: 'msg',
            // 父组件值改变时触发的回调
            observer: () => {
                console.log('i am change')
            }
          }
        },
        data: {
          componentData: {}
        },
      })
    3. 使用自定义组件( 先要在页面的 json 文件中进行引用声明 )

      // 先引用声明
      "usingComponents": {
          // hybg 标签名
          "hybg": "../component/component" // 相对路径
        }
        
        // 直接使用,需要的话要绑定数据
        <hybg></hybg>

    slot 模板

     1. 单 solt  
        "
        // component
        <view>
            <slot></slot>
        </view>
        
        // page ( hybg 是上面的组件标签名)
        <hybg>
            <view> page 的 slot </view>
        </hybg>
        
        // 效果
        <view>
            <view> page 的 slot </view>
        </view>
        
        "
     2. 多slot
        "
        // 先在 Component 的 js 中添加
        options: {
            // 启用多slot
            multipleSlots: true
          },
        // 多 slot 需要使用不同的 name 来区分
        <view>
            <slot></slot>
            <slot></slot>
        </view>
        
        // page ( hybg 是上面的组件标签名)
        <hybg>
            <view> first -- slot </view>
            <view> last-- slot </view>
        </hybg>
        
        // 效果
        <view>
            <view> first -- slot </view>
            <view> last-- slot </view>
        </view>
        
        "

    父子组件事件(子组件传值)

    // page
    fatherEvent: function(e){
        console.log(e.detail) // 组件传递的自定义信息
      }
    <hybg></hybg>
    
     // component
     tap: function(){
      var myEventDetail = { a: 10} // detail对象,提供给事件监听函数
      var myEventOption = {} // 触发事件的配置选项
      // bubbles 事件是否冒泡
      // capturePhase 事件是否拥有捕获阶段
      // composed 是否可以穿越父组件边界
      this.triggerEvent('hybgEvent', myEventDetail, myEventOption)
    }
    
     <view>触发 hybgEvent 事件</view>

    相关推荐:

    微信小程序入门到实战实例分享(四)

    微信小程序授权获取用户详细信息实例

    微信小程序request请求后台接口php代码实例

    The above is the detailed content of Quick knowledge about WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

    The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment