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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool