I. Introduction to MPVUE

Mpvue is a tool that uses vue.js
Develop appletThe front-end framework of the. The framework is based on the Vue.js core,
Mpvue modifies the Runtime and Compiler implementation of vue.js, so that it can run in the small program environment, so as to introduce a complete set of Vue.js development experience for small program development. Mp is
mini programThe abbreviations.

Second, MPVUE fast entry

① Introduce MPVUE template through scaffolding

Vue 3.0 is
The vue init command is not supported, so it needs to be installed separately
@vue/cli-initOnce installed, you can introduce the MPVUE template by following these steps

npm install -g @vue/cli-init

vue init mpvue/mpvue-quickstart my-project

cd my-project

npm install

npm run dev

The NPM run dev command generates a dist directory under the project root, which is
Convert a Vue project to a WeChat applet project

② build a small program development environment

WeChat provides a specialized
WeChat Developer ToolsTo develop small programs, you need to download and install the WeChat developer tools, and you also need to apply for a small program ID, i.e
AppIDBecause the
To create a small program project using the WeChat developer tool, you need to fill in an AppID, you can apply for it on the WeChat public platform.

③ Commissioning project

Start the WeChat applet project with the WeChat developer tool and select the project directory
Is the root directory of the mpvue project, not the generated dist directoryBecause of
The WeChat developer tool does not support viewing.vue files, so we still want to use their own development tools debugging source code.

Three, some details of the use of MPVUE

App.vue root component is just a structure with no concrete content. The root component has a corresponding main.js file to render the app.vue root component, that is, to introduce app.vue and create a Vue instance as a Vue constructor. Then mount, and there is an app.json file, which is the page global configuration file, for registering the page, registering the tabBar, and setting the global window style, such as:

// App.vue


export default {

page {
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;

// main.js

import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue(App)

// app.json

{ "pages": [ "pages/index/main" ], "tabBar": { ...... }, "window": { "backgroundColor":"#00BFFF", "backgroundTextStyle": "light", "navigationBarBackgroundColor": "# FFF ", "navigationBarTitleText": "test ", "navigationBarTextStyle": "black"}

(2) Pages defined in mpvue are placed in the Pages directory under SRC directory, each page corresponds to a folder, each page folder needs to have a. Vue file and main.js file, main.js main is to introduce the corresponding. The Vue instance is then created and mounted as an argument to the Vue constructor, and the name of main.js cannot be changed, only main.

// main.js

import Vue from 'vue' import App from './index' // add this to handle exception Vue.config.errorHandler = function (err)  { if (console && console.error) { console.error(err) } } const app = new Vue(App) app.$mount()

In mpvue, the name of a.vue file on a page can be arbitrary, but
The.js and.json file names are fixed to mainUsually we also fixed the.vue file using index.vue, all
A page usually contains index.vue, main.js, main.json.
Different pages are distinguished by the outer folder, and native applet, also through the outer folder to distinguish different pages, but
The four pages in the folder can have the same or different names as the outer folder, but the four files must be unified.

③ Every time you add a new page, you need to restart the project, that is, re-execute NPM run dev.

Four, WeChat small program foundation and common API

① Click the button to prompt the user whether to authorize and obtain user information

WeChat applet gives us the button
<button>It provides some information
WeChat development capabilities, by adding one to the <button> tag
open-typeAttribute, representing
The type of capability to be opened to the button, such as
getUserInfo, the ability to click the button to get the user’s information, we need to listen on <button>
getuserinfoEvent, MPVUE in the small program on the basis of the package, need to pass
e.mp.detail.userInfoTo get the user’s information,

</button> <script> export default {getUserInfo(e) { console.log(e.mp.detail.userInfo); }} </script>

② WX global object is like a web page running in the browser environment, the browser environment will provide a global Window object, the same small program is running in the small program environment, the small program environment will also provide a global WX object, WX will provide a lot of APIs, For example, access network (wx.request({})), page redirectTo(wx.redirectto ({})), display loading(wx.showLoading({})), display prompt (wx.showToast({})), etc

WeChat in the small program environment can not directly provide Ajax like a browser environment, but provides a global network request API, that is, wx.request(), in the small program environment can only use wx.request() to initiate network request, Commonly used request libraries such as Axios cannot be used, and wx.request() does not have cross-domain issues. When using wx.request(), you pass a request parameter configuration object. Request () returns a result that is not a Promise object, so you cannot process the result of a request using.then(). Instead, callback functions such as Success, Fail and Complete are added to the request configuration object. In the callback function, the result of the request can be obtained, such as:

Wx. request({url: "http://www.baidu.com", // request URL: data: {user: "even li"}, method: "get", // request method header: {" Content-type ": "application/json" // Default}, success(res) {console.log(res.data); }, fail(error) {console.log(error); // Request failed} complete(res) {// The interface call ends, and the request is executed console.log(res) if it succeeds or fails; // Res is the result of the response if the request succeeds, Res is the error message if the request fails.

It’s important to note that,
The request is considered successful if the return status code is 404.
Generally, only when the network exception is considered a request failure.

If you want to jump to a non-tabbar page, you can use a global API, wx.redirectto ({}), which closes the current page and jumps to a page in the app. But you are not allowed to jump to the tabbar page. We need to pass a configuration object whose main attribute is URL, that is, the path to jump to the page, with parameters, and then the callback functions of success, fail and complete. Please process the jump result, such as:

wx.redirectTo({ url: ".. /question/main", // inside a page... Equivalent to pages/success () {}, fail () {}, complete () {}});

In WeChat applet, tabBar pages need to jump in a special way, that is to use wx.switchTab({}), which will jump to tabBar pages and close all other non-tabbar pages. It is used in the same way as wx.redirectTo({});

wx.switchTab({ url: ".. /learn/main", // on a page... Equivalent to pages/success () {}, fail () {}, complete () {}});

⑥ page configuration file small program page configuration file is divided into global configuration file app.json and that page configuration main.json. There are many configurable items in the global configuration file. The entire configuration file content should be enclosed in curly braces, i.e. a JSON object, such as:

  • Pages property is an array, used to define the small program used pages, each item in the array corresponds to a page, that is, path + file name information, do not need to write suffix, in MPVue all pages fixed use main, that is, each page will have a main.js, so in the configuration of Pages, Usually “pages/ page name /main”, the first entry in the Pages array represents the initial page of the applet, that is, the page displayed when the applet is run.
  • Window property, that is, it configures the window style of the applet, and its property value is an object, mainly including backgroundColor(the backgroundColor of the window, that is, the color of the background window that appears after the page is pulled down), backgroundTextStyle(sets the style of the pull-down background font and loading graph), Currently only supports the dark and light), navigationBarBackgroundColor (navigation bar background color), navigationBarTextStyle (navigation title color, Currently only black and white are supported), navigationBarttitleText (navigationBarTitleText content), navigationStyle(value is custom custom navigation bar)

When the WeChat applet sets the color,
Only hexadecimal colors are supported, RGB format and color English are not supported.

  • The tarBar property, used to configure the tabBar at the bottom of the window, is an object that has color(to set the color of tab-inactive text), selectedColor(to set the color of tab-active text), borderStyle(to set the color of the border on the tabBar), Currently, only Black and White are supported), BackgroundColor (to set the backgroundColor of the TAB), List (to configure TAB items, up to 5 items), List attribute value is an array, It mainly includes text(text content displayed on the TAB), iconPath(iconPath displayed when the TAB is not active), selectedPath(iconPath displayed when the TAB is active), pagePath(pagePath to jump to when the TAB is clicked), Its property value is the path configured in the pages.

The page configuration configuration is much simpler than the global master configuration file
Only the style properties of the window can be configured in the page configuration file, that is, you can only configure the contents of the window property in the global configuration file,
The contents of the configuration in the page configuration file overwrite the same configuration in the window in the global configuration fileTo determine the window appearance of the current page,
Instead of using the window property, place the window configuration in curly braces.

⑦ Small program pages and Vue life cycle

The applet provides the page
onLoad(page loading),
onShow(page display,
But it’s not done yet), onReady(page rendering completed),
onHide(page hidden),
onUnload(page unload),
MPVue combines the page life cycle provided by a applet with the life cycle of a Vue, that is, using MPVUE to develop small programs, you can use the life cycle of the small program and the life cycle of VUE at the same time, the order is:
beforeCreate –> created –> onLoad –> onShow –> onReady –> beforeMount –> mounted. namely
Vue is instantiated first and then the page starts to load, display, render, and then the Vue instance starts to mount after the page is rendered.

The so-called navigation to a page, is to jump to a page, but it will retain the current page, jump to the destination of the page navigation bar in the left has a back button, click can go back to the previous page, but the destination of the jump page can not be the page in the tabbar, It uses wx.navigateto ({})

wx.navigateTo({ url: ".. /myLesson/main" // Navigate to my course page, the target page has a back button, click to return to the previous page});

When we click on a specific item in the list, we usually need to dynamically display the specific navigation bar title of the current clicked item on the corresponding page. The WeChat widget provides wx.setNavigationBarTitle({}) for dynamically setting the navigation bar title. There are also three callbacks, success, fail and complete, such as:

Wx. setNavigationBarTitle({title: "dynamic title content ", success() {}, fail() {}, complete() {}});

Attensively local cache data WeChat small program provides setStorage({}) method, which can store data in the key specified in the local cache. Data will always be available unless the user initiatively deletes it or is cleaned up by the system due to storage space reasons. The maximum length of data allowed to be stored by a single Key is 1MB, and all data stores are up to 10MB. Such as:


Similarly, the WeChat applet also provides getStorage({}) method, which is used to get the data stored in the corresponding key. There are three callbacks of success, fail, and complete, such as:

wx.getStorage({ key: "Key ", success (res) {// data in the corresponding key}, fail() {// data in the corresponding key}, complete() {// data in the corresponding key}, }} is executed whether it succeeds or fails;

The getStorage() and setStorage() methods themselves are
asynchronous, but the WeChat applet provides the corresponding synchronization method, i.e
setStorageSync(“key”, “value”);

The WeChat widget provides a

turnkey component, in which only a swiper-item component can be placed, and swiper has some commonly used properties, such as:

  • Indicator-dots: Indicator-dots display on the panel
  • Autoplay: whether to switch automatically;
  • Interval: Set the automatic switching time interval;
  • Duration: the length of the slide animation;
  • Circular: Whether to loop back;
  • Indicator active-color: Sets the color of the currently selected indicator.
<swiper :indicator-dots="indicatorDots" :autoplay="autoPlay" :interval="interval" :duration="duration" : Indicator ="rgba(255,255,255, 0.6)"> <block v-for="(item) index) in imgUrls" :key="index"> <swiper-item> <img :src="item" class="slide-item"/> </swiper-item> </block> </swiper>

Of course, the <swiper> component can do not only rotation of images, but also other kinds of rotation, such as
Rotating list content (navigation and content linkage)Instead of adding indicators -dots, autoplay, interval, duration, circular, etc
Slide by hand, there is one more Swiper component
Property value is the index value of the sliderIs used to display the corresponding sliding item, so as to realize the linkage between navigation and content, i.e
Click the navigation to automatically switch to the corresponding content. The Swiper component also provides a change event, which is triggered when you manually slide an item. You can update the navigation position by retrieving the index of the corresponding slider in the event object
Slide content to automatically highlight navigation position.

Bb0 provides a

  • Scroll -x: whether to allow horizontal scrolling;
  • Scroll-y: whether vertical scrolling is allowed;
  • Scroll into-view: the attribute value is the id of the corresponding scroll item, which means automatically scroll to the position of the corresponding id element;
  • Scroll with-animation: Use the animation transition when setting the scroll bar position;

In order to automatically scroll to the corresponding scroll item position after clicking on a scroll item, we need to add an ID to each scroll item, and then dynamically change the value of scroll into-view to the ID of the corresponding scroll item.

<scroll-view class="btns_wrap" 
             scroll-x :scroll-into-view="toChildView" 
    <span :class="{active: currentIndex === index}" 
          v-for="(item, index) in allLessons"