Introduction to the

Because the project needs, recently did a public account webpage development. A number of potholes were also stepped on during this period, and when these potholes were resolved, the project was ready for review. Record the problems solved by the project from development to online, and summarize the steps of using VUE to develop the public account. It is convenient for future reference. I hope it helps

Project background

The main is an H5 page, the function involved is not very difficult, mainly for a long time did not develop the public number, some unfamiliar to the whole development steps. It includes the way to call wechat SDK, user’s wechat authorization and SDK access, etc. Mainly around the development steps to comb.

start

Since it is an H5 page, the overall project is not big, so I decided to use the VUE framework for development when selecting the project technology. Using VUE to develop H5, I feel the overall efficiency is relatively high. In the UI library is vant library, the component as a whole is good, support custom theme convenient style customization is more suitable for the development of H5.

Create a project using vue-CLI

Scaffolding installation tool

npm install -g @vue/cli
# OR
yarn global add @vue/cli
Copy the code

Create a project

vue create water_project
Copy the code

The project directory is then created

.├ ── ├.md ├── ├.jsConfig.js ├── Package.json ├──.package The favicon. Ico │ └ ─ ─ index. The HTML ├ ─ ─ the SRC │ ├ ─ ─ App. Vue │ ├ ─ ─ API │ ├ ─ ─ assets │ ├ ─ ─ components │ ├ ─ ─ global. Less │ ├ ─ ─ Main. Js │ ├ ─ ─ the mock │ ├ ─ ─ the router │ ├ ─ ─ store │ ├ ─ ─ utils │ └ ─ ─ views └ ─ ─ vue. Config. JsCopy the code

About mobile adaptation

Because it is a mobile web page, so need to do adaptation. There are many adaptation schemes on the Internet, but I will not expand them here. I will mainly say that the scheme used in this project is made by amFE-Flexible combined with REM, which is a solution of Taobao. The postCSS-PxtoREM scheme is used to convert the unit PX of the design draft into REM. In fact, it is possible to use webpack loader to do, the specific scheme is baidu.

  1. The installationamfe-flexiblepackage
npm i amfe-flexible -S
Copy the code
  1. The installationpostcss-pxtoremThe plug-in
npm i postcss-pxtorem -D
Copy the code
  1. Introduced in main.jsamfe-flexible
import "amfe-flexible"
Copy the code
  1. Configure the PostCSS plug-in in vue.config.js

If there is no vue. Config. js file in the project, create one manually. This is the vue CLI configuration file.

css: {
    loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 37.5.propList: ["*"],}),],},},Copy the code

So far the style adaptation has been completed. Why is rootValue 37.5? Mainly for vant adaptation, so the design is 375px as a reference. If no third-party UI library is used, the design draft can be used as a reference and rootValue is 75.

Use the normalize. CSS

Use normalize.css to eliminate basic style differences between browsers

npm i normalize.css -S
Copy the code

Introduced in main.js

import "normalize.css"
Copy the code

Access vant library

Vant is a UI library produced by Yizan. Standing on the shoulders of giants, efficiency is certainly much faster. This third-party library can only be used as a basis for customizing the style if the design is available. Simple styles vant supports theme customization is still convenient, if some styles do not provide a custom theme, you have to write styles to override.

  • Download and install vant
npm i vant -S
Copy the code
  • There are three ways to introduce components, which are also introduced on the official website. For details, you can check the official website.

Method 1. Automatically import components on demand (recommended)

Babel-plugin-import is a Babel plug-in that automatically converts the way import is written to import on demand during compilation.

Install pluginsNPM I babel-plugin-import -d // add configuration to.babelrc // note: webpack 1 does not need to set libraryDirectory {"plugins": [["import", {
      "libraryName": "vant"."libraryDirectory": "es"."style": trueModule.exports = {plugins: [[plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: {plugins: [['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']]};Copy the code
// Then you can introduce Vant components directly into your code
// The plug-in automatically converts the code to the on-demand import form of method 2
import { Button } from 'vant';
Copy the code

Method 2: Manually import components as required

You can manually import the required components without using plug-ins.

import Button from 'vant/lib/button';
import 'vant/lib/button/style';
Copy the code

Method 3: Import all components

Vant supports importing all components at once, which increases the size of the code package and is therefore not recommended.

import Vue from 'vue';
import Vant from 'vant';
import 'vant/lib/index.css';

Vue.use(Vant);
Copy the code

Tips: Direct import of all components is not allowed after configuration is imported on demand.

Customize the Vant theme

Step 1 imports the style source file

To customize a theme, import the Less style file corresponding to the component. You can import the Less style file on demand or manually.

Importing styles on demand (recommended)

Configure the import on demand style source file in babel.config.js. Note that babel6 does not support import on demand styles, please import styles manually.

module.exports = {
  plugins: [['import',
      {
        libraryName: 'vant'.libraryDirectory: 'es'.// Specify the style path
        style: (name) = > `${name}/style/less`,},'vant',]]};Copy the code

Importing styles manually

// Introduce all styles
import 'vant/lib/index.less';

// Introduce a single component style
import 'vant/lib/button/style/less';
Copy the code

Step 2 Modify the style variable

The variable can be modified using modifyVars provided by Less. Here is the webPack configuration for reference.

// webpack.config.js
module.exports = {
  rules: [{test: /\.less$/,
      use: [
        / /... Other Loader Configurations
        {
          loader: 'less-loader'.options: {
            // If the version of less-Loader is earlier than 6.0, remove lessOptions and directly configure options.
            lessOptions: {
              modifyVars: {
                // Override variables directly
                'text-color': '# 111'.'border-color': '#eee'.// Or you can override it with less files (the file path is absolute)
                hack: `true; @import "your-less-file-path.less"; `,},},},},],};Copy the code

If vuE-CLI is set up, you can configure it in vue.config.js.

// vue.config.js
module.exports = {
  css: {
    loaderOptions: {
      less: {
        // If the version of less-Loader is earlier than 6.0, remove lessOptions and directly configure options.
        lessOptions: {
          modifyVars: {
            // Override variables directly
            'text-color': '# 111'.'border-color': '#eee'.// Or you can override it with less files (the file path is absolute)
            hack: `true; @import "your-less-file-path.less"; `,},},},},},},};Copy the code

Introduce wechat JSSDK

There are two ways to introduce the JSSSDK, one is to introduce it directly with js links and write it in index.html.

 <script src="Https://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
Copy the code

Then call window.wx. XXX where it is used to use the SDK provided methods.

The second way is to use the NPM package

  • Install weixin – js – SDK
npm i weixin-js-sdk -S
Copy the code
  • Use in main.js
import wx from "weixin-js-sdk"

// Hang on the vue prototype for easy use
Vue.prototype.$wx = wx;

Copy the code

This.$wx.xx (); this.$wx.xx ();

 this.$wx.config({
          debug: false.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
          appId: res.data.appId, // Mandatory, the unique identifier of the public account
          timestamp: String(res.data.timestamp), // Mandatory to generate the timestamp of the signature
          nonceStr: String(res.data.nonceStr), // Mandatory to generate a random string of signatures
          signature: res.data.signature, // Mandatory, signature, see Appendix 1
          jsApiList: [
            "getNetworkType"."getLocation",].// Mandatory, a list of JS interfaces to be used. See Appendix 2 for a list of all JS interfaces
        });
Copy the code

Register to validate the SDK to use the API

In fact, the important logic of registration is to provide an interface to obtain configuration information at the back end, and the front end directly calls the CONFIG method of SDK for registration. Here we write the SDK registration logic in the app.vue file

  • Encapsulate a method to register the SDK
async getWxJssdkConf() {
      const res = await this.$api.getSdkConfig({
        url: window.location.href.split("#") [0]});if (res.success) {
        this.$wx.config({
          debug: false.// If debug mode is enabled, the return value of all API calls will be displayed in the client alert. If you want to view the parameters passed in, you can open it in the PC, and the parameter information will be printed in the log.
          appId: res.data.appId, // Mandatory, the unique identifier of the public account
          timestamp: String(res.data.timestamp), // Mandatory to generate the timestamp of the signature
          nonceStr: String(res.data.nonceStr), // Mandatory to generate a random string of signatures
          signature: res.data.signature, // Mandatory, signature, see Appendix 1
          jsApiList: [
            "getNetworkType"."getLocation",].// Mandatory, a list of JS interfaces to be used. See Appendix 2 for a list of all JS interfaces
        });
        this.$wx.ready(() = > {
          this.$wx.checkJsApi({
            jsApiList: ["getNetworkType"."getLocation"].// List of JS interfaces to be tested. See Appendix 2 for a list of all JS interfaces.
            success: function (res) {
              console.log("checkJsApi", res); }}); });this.$wx.error((res) = > {
          console.log("wx.error", res); }); }},Copy the code
created() {
    this.getWxJssdkConf();
  },
Copy the code

This.$api.getSdkConfig is the interface to call the background, here is to attach the API to the prototype of vue, convenient to use without every page to import API

Vue.prototype.$api = api
Copy the code

After registering successfully in app.vue, you can use the SDK API.

Authorized by wechat

If you want to obtain the user’s information, you must ask the user to authorize it. The interface provided by wechat is used for authorization. Please see here for details. If only the openID of the user is obtained, only silent authorization can be used, without active authorization by the user. For details, please refer to the documentation. Here, only openID is required to use silent authorization as follows:

  • If it is used in the main entrance that requires authorization, such as the Home page here, it is necessary to call the interface of wechat to obtain the code, and then use the code to exchange for OpenID at the back end
/ * * *@description: Obtain the authorization code *@param {*}
     * @return {*}* /
    getCode() {
      // Intercepts code from window.location.href and assigns the value
      // window.location.href.split('#')[0]
      if (window.location.href.indexOf("state")! = = -1) {
        this.code = qs.parse(
          window.location.href.split("#") [0].split("?") [1]
        ).code;
      } 
      
      if (this.code) {
          // There is code calling interface directly
          this.handGetUserInfo(this.code);
        } else {
          this.handLogin(); }},/ * * *@description: Obtain user authorization to log in *@param {*}
     * @return {*}* /
    handLogin() {
      // Redirect the address to the current page, get the code in the path
      const hrefUrl = window.location.href;

      if (this.code === "") {
        window.location.replace(`
		https://open.weixin.qq.com/connect/oauth2/authorize?appid=XXXXXXXX
                           &redirect_uri=The ${encodeURIComponent(hrefUrl)}
                           &response_type=code
                           &scope=snsapi_base
                           &state=h5#wechat_redirect`); }},/ * * *@description: Get user information *@param {*} code
     * @return {*}* /
    handGetUserInfo(code) {
      // Call the background interface
    },
Copy the code

This is the main logic of authorization, and it works out pretty well without any surprises.

Disconnection prompts

If the user’s network is down, jump to the disconnection prompt page. The judgment logic is written in the app.vue file. Since every page will be prompted, it is directly processed in the main entrance.

mounted() {
    window.addEventListener("online".this.updateOnlineStatus);
    window.addEventListener("offline".this.updateOnlineStatus);
  },
  
 methods: {
 		updateOnlineStatus(e) {
      const { type } = e;
      console.log("type==============", type);
      this.onLine = type === "online"; }},beforeDestroy() {
    window.removeEventListener("online".this.updateOnlineStatus);
    window.removeEventListener("offline".this.updateOnlineStatus);
  },
Copy the code

This is the main method to check the user’s network connection

Determine whether wechat is open the web page

The navigation guard of Vue-Router is mainly used here to judge the browser before jumping. If it is not the built-in browser of wechat, it will directly jump to the abnormal prompt page

router.beforeEach((to, from, next) = > {
  const ua = navigator.userAgent.toLowerCase();
  if( to.path ! = ="/notwx" &&
    !(ua.match(/MicroMessenger/i) = ="micromessenger")
  ) {
    next("/notwx");
  } else{ next(); }});Copy the code

Sometimes jump to the page, the scrolling height of the page will be retained in the previous page scrolling height, here is also solved in the navigation guard, the initiative to scroll to the top

router.afterEach(() = > {
  window.scrollTo(0.0);
});
Copy the code

summary

To this whole development process is simply recorded, but also on their own development of a comb, but also convenient to consult later. Hope to see the article you help, personal opinion, if there is a question welcome to correct, feel helpful, welcome a thumbs-up, thank you.