mpvue

Mpvue is a framework for developing small programs using vue.js. The MPVue framework is based on the Vue.js core. MPVue modified the Runtime and Compiler implementation of Vue.js to enable it to run in a small program environment, thus introducing a complete Vue.js development experience for small program development.

Use the MPVUE framework to develop small programs, can directly use the VUE syntax development.

Vant Weapp

Vant Weapp is a small program UI component library that allows you to use packaged components to implement certain functions, similar to the introduction of the Element component.

flyio

github:https://github.com/wendux/fly Flyio documentation: https://wendux.github.io/dist… As stated on the website, fly.js is a Promise-based, request forwarding HTTP request library that supports all JavaScript runtimes, maximizing code reuse across multiple terminals. Its features: Supports multiple JavaScript running environments Support request/response interceptors Automatic conversion of JSON data Supports switching of low-level HTTP Engine Supports switching of JSON data Supports switching of low-level HTTP Engine 7, Browser side supports global Ajax intercept 8, H5 page embedded in Native APP, support to forward HTTP request to Native, support direct request for pictures

The small program environment built this time will use FLYIO this HTTP request library to achieve data request, currently used methods for GET, POST.

Examples of use of the two are available in the help documents on the official website:

Project initialization

Create a new project Vue init MPVue/MPVue-QuickStart one_hour_app based on the MPVue-QuickStart template

2. Open and run the project

The newly created project opens, and the dist folder does not yet exist

Run up the project

cd one_hour_app

npm run dev

This will give the project a dist folder with a wx folder inside

The wx folder is the file to be imported into the WeChat developer tools. Install WeChat developer tools, open WeChat website downloadable document page: https://developers.weixin.qq…

After installing the WeChat developer tools, click Import Project

Enter the imported directory in the popover

The directory is the same wx under the dist generated after the NPM run dev in the one_hour_app project. To get the AppID, you need to register in the WeChat public platform first, and then open the development-development Settings to find it.

This is shown after successful import

This way, we can write our code in the editor, and then view the page as a browser in the WeChat developer tool.

Looking at the project VUE file, we can see that we can basically write the VUE file as if it were VUE.

After the structure of the project is deleted, the original provided those unused files are deleted first. Preserve an architecture. The main focus of development is the SRC directory.

Remove images and tabs from statics

SRC /main.js remains the same

The SRC/app.vue code will be deleted

SRC /app.json is used to configure the routing Pages, Windows style and text Settings in the header, and Tabbar menu Settings in the foot. For now, only the following is left:

SRC /components/card.vue delete SRC /pages and leave only the index section. Next, delete index.vue.

After finishing trimming, only the home page remains

At this point, based on MPVUE small program project architecture has been set up.

Next is CSS extension language SCSS, Vant Weapp UI component library, FlyIO, MPVUE routing plug-in MPVUE – Router – Patch. 1. Install SCSS. The version of sass-loader is 7.3.1. If you use the latest version, there will be an error.

npm i -D sass-loader node-sass

Under test:



2. Install Vant Weapp

npm i vant-weapp -S --production

Go to Vant Weapp’s website to find an example of a button, but before using it, you need to configure the introduction component in the app.json file.

Since the component is installed in node_modules/vant-weapp/dist,

Therefore, the path of introducing components is different from the one given on the official website, so we need to manually modify the path:

Also, since we need to look in the WeChat developer tool, where the dist/wx is imported, it is different from the directory in the editor, so in order to display the components properly in the WeChat developer tool, we need to do a configuration. Copy the entire node_modules/vant-weapp/dist directory to dist/wx/vant-weapp/dist, and add the following configuration to wePack.base.conf.js:

if (/^wx$/.test(PLATFORM)) {
  baseWebpackConfig = merge(baseWebpackConfig, {
    plugins: [
      new CopyWebpackPlugin([{
        from: resolve('node_modules/vant-weapp/dist'),
        to: resolve('dist/wx/vant-weapp/dist'),
        ignore: ['.*']
      }])
    ]
  })
}


Key Button

The component is introduced successfully and you can see that the configuration of the copy directory is in effect. You can see that the vant-weapp directory has been generated in wx.

3. Install FlyIO, mpvue-router-push

npm i -S flyio
npm i -S mpvue-router-patch

You don’t need the routing plug-in now, so install it and leave it there.

Next is to use FlyIO to implement the request of small program authorization login.

First create request.js in utils to encapsulate FlyIO’s request.

Function createFly () {if (MPVuePlatform === 'wx') {const Fly = require('flyio/dist/ NPM /wx') return new Fly() } else { return null } }
// handle GET requests, POST requests, POST requests, POST requests, Export function get (url, params = {}, showErr = true) { const fly = new createFly() if (fly) { return new Promise((resolve, reject) => { fly.get(url, params).then(response => { const data = (response && response.data) || {} if (data.error_code === 0) { resolve(response) The console. The log (response)} else {the if (showErr) {mpvue. ShowToast ({title: data. MSG | | 'attempt failed, icon:' none ', duration: 1500}); } reject(response) } }).catch(err => { console.log(err) }) }) } }

If a TypeError is encountered: __webpack_require__(…) If this is not a function, close the WeChat Developer Tools, delete the dist package, re-open the NPM Run Dev, and reopen the WeChat Developer Tools.

Next comes the user-authorized content.

Authorized to log in

To display the home page, you need to call mpvue.getSettings to get the user’s current Settings. Authorized to display the normal page, not authorized to display auth.vue authorized login page.

Unauthorized state. When the user agrees to use the authorization, the home page will turn to the normal page. At the same time, the user’s information “userInfo” needs to be obtained.

After successfully retrieving the user information, you need to use the memory mpvue. SetStorageSync to store it for later retrieval using GetStorageSync when you need it. There will be two situations, one where OpenID already exists, and the other where OpenID has not yet been obtained.

When the OpenID is not available, you need to call the interface to get the OpenID, and call the interface to get the code, which is available through the mpvue.login API. When the code is obtained, it calls the interface that retrieves the OpenID, returns the OpenID and stores it. Once you have the OpenID, you can pass the OpenID as a parameter to the interface that gets the home page data.

When the OPENID has been obtained, it directly calls the home interface data and passes the OPENID as the parameter of the interface.

After that, you need to call the Register interface, which stores user behavior data in the background and identifies different users.

Process diagram:

The main button events for the auth.vue component:

<button class="auth-btn" open-type="getUserInfo" @getUserInfo ="getUserInfo"> </button>
getUserInfo () {
      this.$emit('getUserInfo')
    }

SRC/API /index.js is used to store the interface

import { get, Post} from "@/utils/request.js" const API_BASE = "export function getOpenId (params) {return get(`${API_BASE}/openId/get`, params) } export function getHomeData (params) { return get(`${API_BASE}/book/home/v2`, params) } export function register (params) { return post(`${API_BASE}/user/register`, params) }

SRC/API /wechat. Js is used to store WeChat platform related APIs

Import {getOpenId} from '@/ API 'const APP_ID =' Enter the APP_ID of WeChat public platform 'const SECRET =' Enter the SECRET of WeChat public platform '// Export function getSetting (auth, onSuccess, auth) onFail) { mpvue.getSetting({ success (res) { if (res.authSetting[`scope.${auth}`]) { onSuccess(res) } else { onFail(res)  } }, fail (res) { console.log(res) } }) }
Export function getUserInfo (onSuccess, onSuccess) onFail) { mpvue.getUserInfo({ success (res) { onSuccess(res) console.log(res) }, fail (res) { onFail(res) } }) }
// call the OpenID export function getUserOpenID (callback) {mpvue. Login ({// call the Login API to get Code Success (res) { Console. log(res) const {code} = res // This code is the precondition for getOpenID ({code, appID: APP_ID, secret: SECRET }).then(response => { const { openid } = response.data.data mpvue.setStorageSync('openId', openid) callback && callback(openid) }).catch(err => { console.log(err) }) }, fail (res) { console.log(res) } }) }

The index. The vue web page:

<template> <div> <div v-if="isAuth"> <div class="index"> </div> <van-button type="primary"> <div> <div v-button type="primary"> </div v-button > <div> <div> {{userInfo. NICKNAME}} </div> to obtain HOMedata data:  <div>{{ homeData.hotSearch && homeData.hotSearch.num }}</div> </div> </div> <auth v-if="! isAuth" @getUserInfo="init" /> </div> </template>
import { get, post } from '@/utils/request'
import Auth from '@/components/base/auth.vue'
import { getHomeData, register } from '@/api'
import { getSetting, getUserInfo, getUserOpenId } from '@/api/wechat'
  data () {
    return {
      isAuth: false,
      userInfo: {},
      homeData: {}
    }
  },
  mounted () {
    this.init()
  },
GetIndexData (openID, userInfo) {getThomeData ({openID}). Then (response = bb0 {console.log(' getThomeData -----', response) this.homeData = response.data.data }) },
GetUserInfoData () {const oncompletegetOpenId = (openId, userInfo) => {this.getIndexData(openId, userInfo); Register ({openID, platform: mpvuePlatform,... UserInfo}) // Register} getUserInfo(// Get UserInfo(res) => {const {userInfo} = res this.userInfo = userInfo mpvue.getStorageSync('userInfo', userInfo) const openId = mpvue.getStorageSync('openId') if (! OpenId | | openId. Length = = = 0) {/ / not exist openId getUserOpenId ((openId) = > {/ / need to request interface for onCompleteGetOpenId (openId, UserInfo)})} else {oncompletegetOpenID (openID, userInfo) // existing openID}}, (res) => {console.log(res)})}
// To obtain authorization information from the beginning, Mounted call init () {getSettings ('userInfo', (res) => {this.isauth = true console.log(res) this.getUserInfoData()}, (res) => { this.isAuth = false console.log(res) } ) }

Finally, put the diagram of the authorization process: