Meituan applet framework MPvue introductory tutorial

Since writing the United States small program framework MPVue squat guide, out of control, today take advantage of weekend free, to write a MPVue (no friends) simple introduction to the tutorial, this tutorial only for beginners, old birds do not spray.

In addition, I also made a simple project specially for this article. If you are too lazy to build the project from scratch, you can directly go to my Github to clone it locally, install the dependency, and then you can directly develop on this basis without any configuration. If you think this project is helpful, please give me Star by the way. Your support is my biggest motivation, thank you!

Ok, let’s get to the topic. First of all, please allow me to quote the official introduction of MPVue by Meituan

Mpvue is a front-end framework for developing applets using vue.js. The framework is based on vue. js core, and MPvue modifies the runtime and Compiler implementation of vue. js to enable it to run in the environment of small programs, thus introducing a whole set of vue. js development experience for small program development.

The main features

Using MPVue to develop applets, you gain the following capabilities based on the applets technical architecture:

  1. Radical componentized development capabilities: improved code reuse
  2. Complete vue.js development experience
  3. Convenient Vuex data management solution: Easy to build complex applications
  4. Quick WebPack build mechanism: custom build strategy, hotReload during development
  5. Support for using NPM external dependencies
  6. Use vue-CLI command line tool vue.js to quickly initialize the project
  7. H5 code conversion ability to compile into small program object code

The best way to learn is to do it. Let’s go out and run a demo project to see if it’s as good as the official says. If you have any experience with VUE development, you will be familiar with this process. You don’t even need to install other tools to create projects directly with VUE-CLI. If you haven’t installed VUE-CLI before, you should run the command first

npm install --g vue-cli
Copy the code

After installing vue-CLI, we can run a command to automatically build a project (during which we will ask you if you use some tools/plug-ins, please choose y or N according to your actual situation, for those who do not know whether to choose Y or N, choose N).

vue init mpvue/mpvue-quickstart test-wxapp
Copy the code

Then go into the project we created and install the dependencies

cd test-wxapp
npm i
Copy the code

Finally, let’s run our development service

npm run dev
Copy the code

At this time, we open wechat developer tools, select small program, and then create a new project directory, fill in the dist directory test-wxapp/dist under our project directory, you can see the effect

At this point, a basic project is complete, however, the purpose of this article is not to teach you how to build an empty project, for which I think the official tutorial is good enough. Next, let’s delete a few sample files and add pages step by step. First, the project configuration file/SRC /main.js contains the following initial contents:

import Vue from 'vue' import App from './App' Vue.config.productionTip = false App.mpType = 'app' const app = new $mount() export default {Vue(App) App.$mount() export default {// {// The page with the ^ symbol in front of it will be compiled into the home page, other pages can be optional, we will automatically add the webpack entry page into the pages: ['pages/logs/main', '^pages/index/main'], window: { backgroundTextStyle: 'light', navigationBarBackgroundColor: '#fff', navigationBarTitleText: 'WeChat', navigationBarTextStyle: 'black' } } }Copy the code

Pages is the route of the page and Window is the configuration of the page (mostly the configuration of the top bar). These configurations will be packaged into the native applet app.json. It is recommended to take a look at the micro channel method of small program documentation, here do not repeat.

/ SRC /pages/counter/logs / SRC /main.js/config.pages/SRC /main.js/config.pages/SRC /main.js/config.pages/SRC /main.js/config.pages/SRC /main.js/config.pages/SRC /main.js/config.pages Keep only one [‘^pages/index/main’], so there is currently only one index page,

And then we open/SRC/pages/index/index. The vue we delete redundant code inside, with only a basic skeleton

</div> </template> <script> export default {data () {return {}}, methods: {}, created () {} } </script> <style scoped> </style>Copy the code

Tip/SRC /utils/index.js is a public library. There is only one simple formatting date function in tip/SRC /utils/index.js

So far, a clean empty project is OK. Next, let’s optimize some of the anti-human things that wechat native does.

ShowToast, wX. showToast and MPtoast will be used to replace the official wx.showToast. I will not mention many inconvenience, the key is that there is a low base of pit small program, no matter how you set it, there will always be a hook in the popover, sometimes I think the error message is also a hook, which seriously misleads the user. According to the official introduction, MPTOAST has the characteristics of light weight, less configuration, less redundancy, simple use and strong customization

We will introduce and configure from NPM according to the official introduction

npm i vuex
npm i mptoast -D
Copy the code

Add the following code to your project’s main configuration file (typically located in SRC /main.js)

import mpvueToastRegistry from 'mptoast/registry'
mpvueToastRegistry(Vue)
Copy the code

To call this.$mptoast() in js, add one of your registered components to the page. Here is a simple example

<template> <div> <-- omit other code --> <mptoast /> </div> </template> <script> import mptoast from 'mptoast' export default { Components: {mptoast}, data () {return {}}, methods: {showToast () {this.$mptoast(' I am the tip ')},}} </script>Copy the code

It’s pretty simple to use

In the context of an applet, to send an external request, we can only use the wx.request method provided by the applet. However, the code of this method is similar to that of Ajax in the Jquery era, which relies on callback to handle the request response. If there are many layers of callback, There will be many layers of nesting, how will this be acceptable to those of us who are used to async-await?

So, after building the basic project, the first thing we need to do is wrap an asynchronous request method based on promise in wx.Request itself. Let’s start by looking at an official sample code for wx.request

Wx. request({url: 'test.php', // for example, not a real interface address data: {x: ", y: "}, header: {'content-type': Function (res) {console.log(res.data)}})Copy the code

As you can see, each request sends a large number of things, without which most of the items are likely to be fixed for a project, so it is not redundant.

For more wx.request parameters, please refer to wechat official documentation

The first parameter is the URL, which is the address we requested. This parameter should be different every time, but the difference should be only the last part of the URL. The location of the interface name is different. For example, http://www.abc.com/api/member/login all interfaces for the same project The address of the server http://www.abc.com/api/ should are the same, The only difference is the interface name of the stepmother, member/login, so we can split the URL into server address + interface name, which is also convenient for the later online, switch the server address.

The second parameter is the request parameter, the request parameter should be different every time, so we will not change this parameter (in fact, in practical applications, there may be a need for each interface to carry a token, we can also add a unified here, but we will not go into depth here).

The third parameter is the request header, which is usually the same thing in the same project, so we’ll just write it dead. There’s also a parameter called method, the request method, which is not listed here because we’re using the default GET value, but we need to set it up here, because now we have this separation mode, which is basically POST requests, so we’re going to say method:’POST’ as well.

The last one is the callback function that handles the result of the request. In the example, there is only one successful callback. In fact, we should add a handler for the request instance, fail

/ / assume that the following code in ` / SRC/utils/requestMethod js ` let serverPath = 'http://www.abc.com/api/' export function post (url, body) { Return new Promise((resolve,reject) => {wx.request({url: serverPath + url // Concatenate complete URL data: body method:'POST', header: { 'content-type': 'application/json'}, success(res) {resolve(res.data) // reject(ret) {reject(ret) // reject(ret) // reject error message}})})}Copy the code

With this encapsulation, we can import the above file elsewhere and request it using the POST function

The import {post} from '/ SRC/utils/requestMethod. Js / / it is important to note that Let res = await post('member/login',{name:myname})Copy the code

If it’s too much trouble to import this file every time, we can also attach it to the prototype Vue(mpvue) by opening the/SRC /main.js file and adding the following code

import {post} from '/src/utils/requestMethod.js'
Vue.prototype.$post = post
Copy the code

So we can call this.$post() directly in all instances of Vue(mpvue) with one line of code,

Let res = await this.$post('member/login',{name:myname})Copy the code

How’s that? Is it more convenient than native?

Of course, after running up, you may also encounter various problems, here I have to my own problems have done some summary of the United States small program framework MPVue squatting guide, I hope to help you, and the official documentation is also very good oh