search
HomeWeb Front-endJS TutorialDetailed explanation of the steps for developing small programs in mpvue

This time I will bring you a detailed explanation of the steps to develop a small program with mpvue. What are the precautions for developing a small program with mpvue? The following is a practical case, let's take a look.

1. ExampleLife cycle

In addition to the life cycle of Vue itself, mpvue is also compatible with the life cycle of small programs. The hooks of this part of the life cycle come from WeChat Page of the mini program, except for special circumstances, is not recommended to use the life cycle hook of the mini program.

app part:

  • onLaunch, initialize

  • onShow, when the applet starts, or Entering the foreground from the background displays

  • onHide. When the applet enters the background from the foreground,

page part:

  • onLoad, monitor page loading

  • onShow, monitor page display

  • onReady, monitor page initial rendering completed

  • onHide, monitor page hiding

  • onUnload, monitor page unloading

  • onPullDownRefresh, monitor user Pull-down action

  • onReachBottom, handler function for page pull-down event

  • onShareAppMessage, user clicks the upper right corner to share

  • onPageScroll, page scrolling

  • onTabItemTap, when the current tab page is clicked, triggered when tab is clicked (mpvue 0.0.16 supports)

Usage example:

new Vue({
  data: {
    a: 1
  },
  created () {
    // `this` 指向 vm 实例
    console.log('a is: ' + this.a)
  },
  onShow () {
    // `this` 指向 vm 实例
    console.log('a is: ' + this.a, '小程序触发的 onshow')
  }
})
// => "a is: 1"

Note:

  1. Do not use arrow functions on option properties or callbacks, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()). Because arrow functions are bound to the parent context, this will not be the Vue instance as you would expect, and this.a or this.myMethod will be undefined.

  2. The query parameter of the WeChat applet page is obtained through onLoad. mpvue has optimized this and directly passes this.$root.$mp.query To obtain the corresponding parameter data, its call needs to be used after the onLoad life cycle is triggered, such as onShow, etc.

2. Template syntax

Does not support pure-HTML

All BOM/DOM in the mini program cannot be used, which means that the v-html command cannot be used.

Does not support some complex JavaScript rendering expressions

We will directly encode the {{}} double curly brackets in the template into the wxml file. Due to the capability limitations of the WeChat applet (Data binding), complex JavaScript expressions cannot be supported.

Currently available are - * % ?: ! == === >

Filters are not supported

The rendering part will be converted to wxml. wxml does not support filters, so this part of the function is not supported.

Function not supported

Using functions in methods within template is not supported.

List rendering

Full support for official documents: list rendering

Just need to pay attention to one thing,nested list rendering must specify different index!

<!-- 在这种嵌套循环的时候, index 和 itemIndex 这种索引是必须指定,且别名不能相同,正确的写法如下 -->
<template>
    <ul>
        <li>
            {{item.value}}
        </li>
    </ul>
</template>

Event handler

The change event in input and textarea will be converted into a blur event.

Note:

  • #For native events not in the list, you can also use the bindregionchange event to directly change the bind to @# on the dom. ## @regionchange, at the same time, this event is also very special. It has two event types: begin and end
    , which makes it impossible for us to distinguish what event it is in handleProxy, so you can listen to events at the same time when listening to such events. Both name and event type

       <map><map></map></map>
  • 小程序能力所致,bind 和 catch 事件同时绑定时候,只会触发 bind ,catch 不会被触发,要避免踩坑。

  • 事件修饰符

    - .stop 的使用会阻止冒泡,但是同时绑定了一个非冒泡事件,会导致该元素上的 catchEventName 失效!
    • .prevent 可以直接干掉,因为小程序里没有什么默认事件,比如submit并不会跳转页面

    • .capture 支持 1.0.9

    • .self 没有可以判断的标识

    • .once 也不能做,因为小程序没有 removeEventListener, 虽然可以直接在 handleProxy 中处理,但非常的不优雅,违背了原意,暂不考虑

  • 其他 键值修饰符 等在小程序中压根没键盘,所以。。。

三、组件

有且只能使用单文件组件(.vue 组件)的形式进行支持。其他的诸如:动态组件,自定义 render,和

详细的不支持列表:

  • 暂不支持在组件引用时,在组件上定义 click 等原生事件、v-show(可用 v-if 代替)和 class style 等样式属性(例: 样式是不会生效的),因为编译到wxml,小程序不会生成节点,建议写在内部顶级元素上。

  • Slot(scoped 暂时还没做支持)

  • 动态组件

  • 异步组件

  • inline-template

  • X-Templates

  • keep-alive

  • transition

  • class

  • style

小程序组件

mpvue 可以支持小程序的原生组件,比如: picker,map 等,需要注意的是原生组件上的事件绑定,需要以 vue 的事件绑定语法来绑定,如 bindchange="eventName" 事件,需要写成 @change="eventName"

示例代码:

<picker>
    <view>
      当前选择: {{date}}
    </view>
</picker>

四、常见问题

1. 如何获取小程序在 page onLoad 时候传递的 options

在所有 页面 的组件内可以通过 this.$root.$mp.query 进行获取。

2. 如何获取小程序在 app onLaunch/onShow 时候传递的 options

在所有的组件内可以通过 this.$root.$mp.appOptions 进行获取。

3. 如何捕获 app 的 onError

由于 onError 并不是完整意义的生命周期,所以只提供一个捕获错误的方法,在 app 的根组件上添加名为 onError 的回调函数即可。如下:

export default {
   // 只有 app 才会有 onLaunch 的生命周期
   onLaunch () {
       // ...
   },
   // 捕获 app error
   onError (err) {
       console.log(err)
   }
}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

前端中排序算法实例详解

JS中使用接口步骤详解

The above is the detailed content of Detailed explanation of the steps for developing small programs in mpvue. 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 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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.