VueJs Project Notes

Posted by pleigh on Thu, 13 Jun 2019 23:55:15 +0200

====================== Summary of Knowledge Points===========================

1. keep-alive (realizing page caching)

2. Solutions for fixed location of mobile terminals

III. Verification of Vue Forms

Lateral sliding tab tab, and input method positioning related

  • JQ Plug-in Network http://jq22.com

  • When the first input box automatically gets the cursor, the pop-up input method will top the layout.

Question 1: Tables that can slide left and right

  • Introduce the Jq framework and tab plug-in into the project

When the first input box automatically gets the cursor, the pop-up input method will top the layout?

  • Add absolute positioning to the outermost box and set a fixed height

        .reg-layer {
          width: 100%;
          height: 360px;
          background: #ffffff;
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          right: 0;
        }
  • Fixed the login box again

        .login-main {
          width: 100%;
          height: 4rem;
          background-color: #ffffff;
          padding-top: 0.4rem;
        }
    

How to load doubles, doubles, triples, etc.

  • Use Retina.js

Pull-Up Refresh, Pull-Down Load More

Log in and register

  • VueJs saves token

  • Judging token failure

VueJs saves token

Vue-cli proxyTable Solves Cross-domain Problems in Development Environment

Using local Storage to solve the problem that vuex data is cleared after page refresh

How to realize the routing jump judgment user rights function in vue?

Axios

Ju Network Status By JS

Web App Notes

Axios WebSite Address

No NetWork SPA

VueJS Communication among brothers

Web pack multi-page Application Architecture Series

Analysis of Vue-Cli Configuration File

Dropdown refresh

Vue-Cli Packaged Publishing

Mobile-webkit-user-select:none causes input/textarea input boxes to fail to enter

VueJs judges Token expiration

delete request in Axios

VueJs Mobile Image Compression Upload

React Note

Refresh Current Page

_this.$router.go(0);

How I can config https in Vue-Cli

use Vue-Scroller

    {
    test: /vue-scroller.src.*?js$/,
    loader: 'babel-loader'
  }
  • It can invoked inflate() method automatically when vue component is mounted,there is a way to solve this problem

        this.$refs.my_scroller.finishInfinite(true); 
    

Wechat share in VueJs Projects

Wechat Public Number

UpLoad File In VueJs

Show PDF In Broswer

Show PDF In Broswer Code

  • http://localhost:63342/pdf.js...

  • it must be contain a canvas tag

    import PDFJS from 'pdfjs-dist';
    showPDF(){

        let pdfPath = '/static/compressed.tracemonkey-pldi-09.pdf';
        let  loadingTask = PDFJS.getDocument(pdfPath);
        loadingTask.promise.then(function (pdfDocument) {
          // Request a first page
          return pdfDocument.getPage(1).then(function (pdfPage) {
            console.log("pdfPage is :",pdfPage);
            // Display page on the existing canvas with 100% scale.
            let scale = 1.5;    
            let viewport = pdfPage.getViewport(scale);
            let canvas = document.getElementsByClassName('theCanvas');
            canvas.width = viewport.width;
            canvas.height = viewport.height;
            let ctx = canvas.getContext('2d');
            let renderTask = pdfPage.render({
              canvasContext: ctx,
              viewport: viewport
            });
            return renderTask.promise;
          });
        }).catch(function (reason) {
          console.error('Error: ' + reason);
        });
      },
    

DownLoad files

How does PDF.js load all pdf contents at once

How to distinguish between uploading files (pdf, word, etc.)?

  • http://blog.csdn.net/shenshen...

  • article/details/21626315

  • accept="application/msexcel" - - corresponding to uploading excel

  • accept="application/msword" - - corresponding to upload word

  • accept="application/pdf" - - corresponding to upload pdf

PDF.js Example

PDF.js Frequently Asked Questions

PDFViewer.vue

<template>
  <div class="pdf-view-layout">
    <header>
      <h1 id="title"></h1>
    </header>

    <div id="viewerContainer">
      <div id="viewer" class="pdfViewer"></div>
    </div>

    <div id="loadingBar">
      <div class="progress"></div>
      <div class="glimmer"></div>
    </div>

    <div id="errorWrapper" hidden="true">
      <div id="errorMessageLeft">
        <span id="errorMessage"></span>
        <button id="errorShowMore">
          More Information
        </button>
        <button id="errorShowLess">
          Less Information
        </button>
      </div>
      <div id="errorMessageRight">
        <button id="errorClose">
          Close
        </button>
      </div>
      <div class="clearBoth"></div>
      <textarea id="errorMoreInfo" hidden="true" readonly="readonly"></textarea>
    </div>

    <footer>
      <button class="toolbarButton pageUp" title="Previous Page" id="previous" @click="goNextPage()"></button>
      <button class="toolbarButton pageDown" title="Next Page" id="next"></button>

      <input type="number" id="pageNumber" class="toolbarField pageNumber"  size="4" min="1" >
      <button class="toolbarButton zoomOut" title="Zoom Out" id="zoomOut"></button>
      <button class="toolbarButton zoomIn" title="Zoom In" id="zoomIn"></button>
    </footer>
  </div>
</template>
<script>
  //Loading PDFJS
  import pdf from '../../../node_modules/pdfjs-dist/build/pdf.js';
  import pdfViewer from '../../../node_modules/pdfjs-dist/web/pdf_viewer.js';
  import Viewer from '../../assets/js/viewer';
  export default{
    data(){
      return{
        myPage:1,
      }
    },
    mounted(){
        const url = 'http://192.168.0.200:8080/media/avatar/fluent-python.pdf';
        Viewer.animationStartedPromise.then(function () {
          Viewer.open({
            url: url
          });
        });
    },
    methods:{
      goNextPage(){
          console.log('Data on the next page');
      }
    },
    watch:{
      myPage(newV,oldV){
          console.log("==================: ",$('#pageNumber').val());
      }
    },
  }
</script>
<style scoped>
  @import "../../assets/css/viewer.css";
</style>

viewer.js

/* Copyright 2016 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals PDFJS */

'use strict';

if (!PDFJS.PDFViewer || !PDFJS.getDocument) {
  alert('Please build the pdfjs-dist library using\n' +
        '  `gulp dist-install`');
}

PDFJS.useOnlyCssZoom = true;
PDFJS.disableTextLayer = true;
PDFJS.maxImageSize = 1024 * 1024;
PDFJS.workerSrc = '../../../node_modules/pdfjs-dist/build/pdf.worker.js';
PDFJS.cMapUrl = '../../../node_modules/pdfjs-dist/cmaps/';
PDFJS.cMapPacked = true;
//Files for pdf to be loaded
// var DEFAULT_URL = 'https://cdn.rawgit.com/mozilla/pdf.js/c6e8ca86/test/pdfs/calrgb.pdf';
// var DEFAULT_URL = 'http://192.168.0.200:8080/media/avatar/fluent-python.pdf';
var DEFAULT_SCALE_DELTA = 1.0;
var MIN_SCALE = 0.25;
var MAX_SCALE = 100.0;
var DEFAULT_SCALE_VALUE = 'auto';

var PDFViewerApplication = {
  pdfLoadingTask: null,
  pdfDocument: null,
  pdfViewer: null,
  pdfHistory: null,
  pdfLinkService: null,

  /**
   * Opens PDF document specified by URL.
   * @returns {Promise} - Returns the promise, which is resolved when document
   *                      is opened.
   */
  open: function (params) {
    if (this.pdfLoadingTask) {
      // We need to destroy already opened document
      return this.close().then(function () {
        // ... and repeat the open() call.
        return this.open(params);
      }.bind(this));
    }

    var url = params.url;
    var self = this;
    this.setTitleUsingUrl(url);

    // Loading document.
    var loadingTask = PDFJS.getDocument(url);
    this.pdfLoadingTask = loadingTask;

    loadingTask.onProgress = function (progressData) {
      self.progress(progressData.loaded / progressData.total);
    };

    return loadingTask.promise.then(function (pdfDocument) {
      // Document loaded, specifying document for the viewer.
      self.pdfDocument = pdfDocument;
      self.pdfViewer.setDocument(pdfDocument);
      self.pdfLinkService.setDocument(pdfDocument);
      self.pdfHistory.initialize(pdfDocument.fingerprint);
      self.loadingBar.hide();
      self.setTitleUsingMetadata(pdfDocument);
    }, function (exception) {
      var message = exception && exception.message;
      var l10n = self.l10n;
      var loadingErrorMessage;

      if (exception instanceof PDFJS.InvalidPDFException) {
        // change error message also for other builds
        loadingErrorMessage = l10n.get('invalid_file_error', null,
          'Invalid or corrupted PDF file.');
      } else if (exception instanceof PDFJS.MissingPDFException) {
        // special message for missing PDFs
        loadingErrorMessage = l10n.get('missing_file_error', null,
          'Missing PDF file.');
      } else if (exception instanceof PDFJS.UnexpectedResponseException) {
        loadingErrorMessage = l10n.get('unexpected_response_error', null,
          'Unexpected server response.');
      } else {
        loadingErrorMessage = l10n.get('loading_error', null,
          'An error occurred while loading the PDF.');
      }

      loadingErrorMessage.then(function (msg) {
        self.error(msg, {message: message});
      });
      self.loadingBar.hide();
    });
  },

  /**
   * Closes opened PDF document.
   * @returns {Promise} - Returns the promise, which is resolved when all
   *                      destruction is completed.
   */
  close: function () {
    var errorWrapper = document.getElementById('errorWrapper');
    errorWrapper.setAttribute('hidden', 'true');

    if (!this.pdfLoadingTask) {
      return Promise.resolve();
    }

    var promise = this.pdfLoadingTask.destroy();
    this.pdfLoadingTask = null;

    if (this.pdfDocument) {
      this.pdfDocument = null;

      this.pdfViewer.setDocument(null);
      this.pdfLinkService.setDocument(null, null);
    }

    return promise;
  },

  get loadingBar() {
    var bar = new PDFJS.ProgressBar('#loadingBar', {});

    return PDFJS.shadow(this, 'loadingBar', bar);
  },

  setTitleUsingUrl: function pdfViewSetTitleUsingUrl(url) {
    this.url = url;
    var title = PDFJS.getFilenameFromUrl(url) || url;
    try {
      title = decodeURIComponent(title);
    } catch (e) {
      // decodeURIComponent may throw URIError,
      // fall back to using the unprocessed url in that case
    }
    this.setTitle(title);
  },

  setTitleUsingMetadata: function (pdfDocument) {
    var self = this;
    pdfDocument.getMetadata().then(function(data) {
      var info = data.info, metadata = data.metadata;
      self.documentInfo = info;
      self.metadata = metadata;

      // Provides some basic debug information
      console.log('PDF ' + pdfDocument.fingerprint + ' [' +
                  info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() +
                  ' / ' + (info.Creator || '-').trim() + ']' +
                  ' (PDF.js: ' + (PDFJS.version || '-') +
                  (!PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');

      var pdfTitle;
      if (metadata && metadata.has('dc:title')) {
        var title = metadata.get('dc:title');
        // Ghostscript sometimes returns 'Untitled', so prevent setting the
        // title to 'Untitled.
        if (title !== 'Untitled') {
          pdfTitle = title;
        }
      }

      if (!pdfTitle && info && info['Title']) {
        pdfTitle = info['Title'];
      }

      if (pdfTitle) {
        self.setTitle(pdfTitle + ' - ' + document.title);
      }
    });
  },
  /**
   * Setting title title title
   * @param title
   */
  setTitle: function pdfViewSetTitle(title) {
    document.title = title;
    console.log("document.title:",document.title,document,document.getElementById('title').textContent);
    if(document.getElementById('title').textContent!==''){
      document.getElementById('title').textContent = title;
    }
  },

  error: function pdfViewError(message, moreInfo) {
    var l10n = this.l10n;
    var moreInfoText = [l10n.get('error_version_info',
      {version: PDFJS.version || '?', build: PDFJS.build || '?'},
      'PDF.js v{{version}} (build: {{build}})')];

    if (moreInfo) {
      moreInfoText.push(
        l10n.get('error_message', {message: moreInfo.message},
          'Message: {{message}}'));
      if (moreInfo.stack) {
        moreInfoText.push(
          l10n.get('error_stack', {stack: moreInfo.stack},
            'Stack: {{stack}}'));
      } else {
        if (moreInfo.filename) {
          moreInfoText.push(
            l10n.get('error_file', {file: moreInfo.filename},
              'File: {{file}}'));
        }
        if (moreInfo.lineNumber) {
          moreInfoText.push(
            l10n.get('error_line', {line: moreInfo.lineNumber},
              'Line: {{line}}'));
        }
      }
    }

    var errorWrapper = document.getElementById('errorWrapper');
    errorWrapper.removeAttribute('hidden');

    var errorMessage = document.getElementById('errorMessage');
    errorMessage.textContent = message;

    var closeButton = document.getElementById('errorClose');
    closeButton.onclick = function() {
      errorWrapper.setAttribute('hidden', 'true');
    };

    var errorMoreInfo = document.getElementById('errorMoreInfo');
    var moreInfoButton = document.getElementById('errorShowMore');
    var lessInfoButton = document.getElementById('errorShowLess');
    moreInfoButton.onclick = function() {
      errorMoreInfo.removeAttribute('hidden');
      moreInfoButton.setAttribute('hidden', 'true');
      lessInfoButton.removeAttribute('hidden');
      errorMoreInfo.style.height = errorMoreInfo.scrollHeight + 'px';
    };
    lessInfoButton.onclick = function() {
      errorMoreInfo.setAttribute('hidden', 'true');
      moreInfoButton.removeAttribute('hidden');
      lessInfoButton.setAttribute('hidden', 'true');
    };
    moreInfoButton.removeAttribute('hidden');
    lessInfoButton.setAttribute('hidden', 'true');
    Promise.all(moreInfoText).then(function (parts) {
      errorMoreInfo.value = parts.join('\n');
    });
  },

  progress: function pdfViewProgress(level) {
    var percent = Math.round(level * 100);
    // Updating the bar if value increases.
    if (percent > this.loadingBar.percent || isNaN(percent)) {
      this.loadingBar.percent = percent;
    }
  },

  get pagesCount() {
    return this.pdfDocument.numPages;
  },

  set page(val) {
    this.pdfViewer.currentPageNumber = val;
  },

  get page() {
    return this.pdfViewer.currentPageNumber;
  },

  zoomIn: function pdfViewZoomIn(ticks) {
    var newScale = this.pdfViewer.currentScale;
    do {
      newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
      newScale = Math.ceil(newScale * 10) / 10;
      newScale = Math.min(MAX_SCALE, newScale);
    } while (--ticks && newScale < MAX_SCALE);
    this.pdfViewer.currentScaleValue = newScale;
  },

  zoomOut: function pdfViewZoomOut(ticks) {
    var newScale = this.pdfViewer.currentScale;
    do {
      newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
      newScale = Math.floor(newScale * 10) / 10;
      newScale = Math.max(MIN_SCALE, newScale);
    } while (--ticks && newScale > MIN_SCALE);
    this.pdfViewer.currentScaleValue = newScale;
  },

  initUI: function pdfViewInitUI() {
    var linkService = new PDFJS.PDFLinkService();
    this.pdfLinkService = linkService;

    this.l10n = PDFJS.NullL10n;

    var container = document.getElementById('viewerContainer');
    var pdfViewer = new PDFJS.PDFViewer({
      container: container,
      linkService: linkService,
      l10n: this.l10n,
    });
    this.pdfViewer = pdfViewer;
    linkService.setViewer(pdfViewer);

    this.pdfHistory = new PDFJS.PDFHistory({
      linkService: linkService
    });
    linkService.setHistory(this.pdfHistory);

    document.getElementById('previous').addEventListener('click', function() {
      PDFViewerApplication.page--;
    });

    document.getElementById('next').addEventListener('click', function() {
      PDFViewerApplication.page++;
    });

    document.getElementById('zoomIn').addEventListener('click', function() {
      PDFViewerApplication.zoomIn();
    });

    document.getElementById('zoomOut').addEventListener('click', function() {
      PDFViewerApplication.zoomOut();
    });

    document.getElementById('pageNumber').addEventListener('click', function() {
      this.select();
    });

    document.getElementById('pageNumber').addEventListener('change',
        function() {
      PDFViewerApplication.page = (this.value | 0);

      // Ensure that the page number input displays the correct value, even if the
      // value entered by the user was invalid (e.g. a floating point number).
      if (this.value !== PDFViewerApplication.page.toString()) {
        this.value = PDFViewerApplication.page;
      }
    });

    container.addEventListener('pagesinit', function () {
      // We can use pdfViewer now, e.g. let's change default scale.
      pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
    });

    container.addEventListener('pagechange', function (evt) {
      var page = evt.pageNumber;
      var numPages = PDFViewerApplication.pagesCount;

      document.getElementById('pageNumber').value = page;
      document.getElementById('previous').disabled = (page <= 1);
      document.getElementById('next').disabled = (page >= numPages);
    }, true);
  }
};

document.addEventListener('DOMContentLoaded', function () {
  PDFViewerApplication.initUI();
}, true);

(function animationStartedClosure() {
  // The offsetParent is not set until the PDF.js iframe or object is visible.
  // Waiting for first animation.
  PDFViewerApplication.animationStartedPromise = new Promise(
    function (resolve) {
      window.requestAnimationFrame(resolve);
    });
})();

/*// We need to delay opening until all HTML is loaded.
PDFViewerApplication.animationStartedPromise.then(function () {
  PDFViewerApplication.open({
    url: DEFAULT_URL
  });
});*/
export default PDFViewerApplication;

VueJs prevents flickering of pages

Processing TextArea Automatically Adapts Height to Text Height

The Width of option in PC and Mobile

Search Layout Problem - Subcomponents to Solve

  • Routing switch (tab switch) implements different layouts

The Wonderful Use of VueJs NextTick

Back to the original rolling position and back to the top (to be improved)

  • Store the location of the scroll when the road is out of state

  • When the routing is in the state of entry, the scroll position is taken out for judgment to display or hide the "Back to the Top" button.

VueJs Automated Testing

A line of text in Web App can not be displayed. The left side is represented by..

Refresh

  • this.$router.go(0);

VueJs Packaging Optimization

Configuration of static resource url in WebPack

Vue-Cli webpack configuration

Integration of Mobile Rich Text Box

The Difference and Relation between push and replace in Vue-Router

VueJs Rich Text Box (Posting Function)

div sets the contentEditable property. Normal on android, Problems on IOS

  • Using div to simulate input or textarea for content input, the function of rich text box is realized.

  • Meeting problems

        Add style="-webkit-user-select: auto" and the cursor and edit will appear.
    

Vuejs-Cordova-Framework-Webapp

Css-Scroller

Scroll Open Source Library for List Scrolling Animation

H5 Control Ban Screen

Donot Upload

Interception of window.open (completed)

  • By borrowing a tag and generating random target

`

                s4() {
                  return Math.floor((1 + Math.random()) * 0x10000)
                  .toString(16)
                  .substring(1);
                },
                JsGuid() {
                return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
                  this.s4() + '-' + this.s4() + this.s4() + this.s4();
                },
        
                 newWin(url, id,target) {
                  let a = document.createElement('a');
                  a.setAttribute('href', url);
                  a.setAttribute('target', target);
                  a.setAttribute('id', id);
                  // Prevent repeated addition
                  if(!document.getElementById(id)) {
                    document.body.appendChild(a);
                  }
                  a.click();
                },

`

  • call

        this.newWin(localStorage.getItem('url'),"dow","csa"+this.JsGuid());
    

Log tool class (easy to debug and print during development) hides all log information after online

  • code

    /**

    • Created by THINK on 2017/7/3.

    • Logging Tool Class: In the development phase, set flag to true (see log) and false (invisible log) when online.

    • @author:darkCode

    • @description:it is a logcat tool,you can use it see all logs you want to see conveniently when developing,and you can hide all logs by set the value of flag is false in this instance when producting
      */

    let logUtil = {
    flag:true,
    printLog(...items){

    if(this.flag){
      console.log(items);
    }

    }
    }
    export default logUtil

Repair pull-up refresh, pull-down load

  • Vue-scroller (automatically loads more bugs)

Optimizing the operation of the project

  • code reuse

  • Processing of resources

Android Simulator Testing

  • Installation Problems: Enter Bios System Settings Hardware Virtualization

Virtualization technology can be turned on in BIOS by the following methods:

1. Enter BIOS. Press F2 or F12 or DEL or ESC when booting (different computers).
2. After entering BIOS, find the Configuration option, select Intel Virtual Technology and return, move the cursor to Enabled, then return, and finally press F10 to save and exit.
If you can't find the Configuration option, try the following:
(1) When some HP computers enter BIOS, they need to select the System Configuration menu, then choose Device Configuration, find Virtualization Technology and set it to Enabled.
(2) When some Lenovo Thinkpad computers enter BIOS, they need to select the Security menu, then select Virtualization and set it to Enabled.
(3) When some Dell computers enter BIOS, they need to select the Processor Settings menu, then select Virtualization Technology and set it to Enabled.
The concept of virtualization was first proposed in 1960 to describe virtual machines (experimental IBM M44/44X systems). The installation and management of virtual machines is called platform virtualization, and now it is also called server virtualization.

Packing business logic code separately from tripartite code

  • Configuration in entry entry entry entry, such as separating jQuery

  • Default production of three js files after packaging with vue-cli

    • app.43fcdsfcafds.js: Code for the business logic you write in the project

    • Vender.20 deewdew32eed.js: Download dependent JS through npm install, CSS code (under node_modules directory)

    • manifest.4cbcd0f5d52237fb29b0.js: Cache the detection file, pack it each time, and check the version through the file

  • Packaging resources in production and development environments
    vender:3.34m app:1.26m, how to reduce their volume

  • Function of vender.xsaxsxx.js.map file

The source map file is a meta-information data file, which is replaced by the variable name of the file and the location of the variable after the compression of the JS file. Generally, this file and the min.js main file are placed in the same directory. For example, the original variable is map after compression, and the rule of variable replacement may be replaced by a after compression. At this time, the source map file will record the mapping information. This advantage is that when debugging, if there are some JS errors, the browser will parse the map file to re-merge the compressed js, so that developers can debug it with the code before uncompression. This will bring us great convenience!

On-demand File Loading (Finishing) - - A Big Step in Project Optimization

  • Load components on demand according to vue routing

  • On-Demand Loading of vue Components: Solves the shortcoming of too large app.xscs3243rcds.js file after packaging

  • Further optimization (three-party js file is not moving, loaded through cdn)

  • Referring to the same module, duplicate resources will appear after packaging, and the three parties will be packaged separately.

Web Pack Code Segmentation

WebPack Chinese Network

VueJs Seo(Nuxt.js)

WeChat Wechat Sharing

Introduction of weixin-js-sdk in Vue-Cli

     isWeiXin(){
        //Determine whether it's a Wechat browser or not?
        let ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) === 'micromessenger') {
          return true;
        } else {
          return false;
        }
      },
  • Sharing implementation process

    • Installation of Wechat SDK NPM install weixin-js-sdk--save-dev

    • (2) Introduce it into the required components through import or require

    • (3) Obtaining signature-related information

    • 4. Verify configuration by injecting privileges through config interface

       wx.config({
      debug: true, 
      appId: '', // Mandatory, Unique Identification of Public Number
      timestamp: , // Mandatory, time stamp for signature generation
      nonceStr: '', // Compulsory, generating random strings of signatures
      signature: '',// Mandatory, signature, see Appendix 1
      jsApiList: [] // Mandatory. List of JS interfaces to be used. All JS interfaces are listed in Appendix 2.
      });
      
    • _Successful Verification through ready Interface Processing

          wx.ready(function(){
      // Config information validation will execute the ready method. All interface calls must be obtained after the config interface gets the result. Config is an asynchronous operation of the client. Therefore, if the relevant interface is required when the page is loaded, the relevant interface must be put in the ready function to ensure the correct execution. For the interface that is called only when the user triggers, it can be called directly without being placed in the read function.
              //Sharing operations
               //Share in the circle of friends
                wx.onMenuShareTimeline({
                  title: 'Test information', // Share titles
                  link: '', // Share links. The link domain name or path must be the same as the public number JS secure domain name corresponding to the current page.
                  imgUrl: '', // Sharing icons
                  success: function (res) {
                    // Callback function executed after user confirms sharing
                    logUtil.printLog("Share the successful information returned from the circle of friends as follows:",res);
                  },
                  cancel: function (res) {
                    // Callback functions executed after users cancel sharing
                    logUtil.printLog("Cancel sharing the information returned to the circle of friends as follows:",res);
                  }
                });
                //Share with friends
                wx.onMenuShareAppMessage({
                  title: '', // Share titles
                  desc: '', // Sharing Description
                  link: '', // Share links. The link domain name or path must be the same as the public number JS secure domain name corresponding to the current page.
                  imgUrl: '', // Sharing icons
                  type: '', // Sharing type, music, video or link, not default to link
                  dataUrl: '', // If type is music or video, provide data links, which are empty by default
                  success: function (res) {
                    // Callback function executed after user confirms sharing
                    logUtil.printLog("The information shared to friends on successful returns is:",res);
                  },
                  cancel: function (res) {
                    // Callback functions executed after users cancel sharing
                    logUtil.printLog("Cancel sharing information returned to friends as follows:",res);
                  }
                });
                //Share QQ
                wx.onMenuShareQQ({
                  title: '', // Share titles
                  desc: '', // Sharing Description
                  link: '', // Sharing links
                  imgUrl: '', // Sharing icons
                  success: function (res) {
                    // Callback function executed after user confirms sharing
                    logUtil.printLog("Share QQ The message that a friend successfully returned is:",res);
                  },
                  cancel: function (res) {
                    // Callback functions executed after users cancel sharing
                    logUtil.printLog("Cancel Sharing QQ Friends return information as follows:",res);
                  }
                });
                //Share QQ space
                wx.onMenuShareQZone({
                  title: '', // Share titles
                  desc: '', // Sharing Description
                  link: '', // Sharing links
                  imgUrl: '', // Sharing icons
                  success: function (res) {
                    // Callback function executed after user confirms sharing
                    logUtil.printLog("Share QQ The successful information returned by space is:",res);
                  },
                  cancel: function (res) {
                    // Callback functions executed after users cancel sharing
                    logUtil.printLog("Cancel sharing QQ The information returned by space is:",res);
                  }
                });
      });
      
    • Dealing with Failure Verification through Eror Interface

      • wx.error(function(res){
        // Failure to verify config information will execute error function, such as signature expiration leading to verification failure. Specific error information can be viewed in debug mode of config or in the return res parameter. For SPA, the signature can be updated here.

    });

  • The signature is composed of: noncestr (signature random string, random writing), jsapi_ticket (ticket), timestamp (timestamp), URL (all lowercase) and so on.

  • Get access_token

    Request interface: https://api.weixin.qq.com/cgi-bin/token?Grant_type=client_credential&appid=your appid&secret=your secret
     Request method: get
     Return result: access_token (valid for 7200 seconds, must be cached on the server) 
  • Get the ticket jsapi_ticket

    Request interface: https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=access_token&type=jsapi obtained in the previous step
     Request method: get,
    type: JSON,
    Return result: jsapi_ticket (valid for 7200 seconds, must be cached on the server)
  • Generate timestamp

    // Timestamp Generation Function
    var timeStamp = function () {
        return parseInt(new Date().getTime() / 1000) + '';
    };
    
  • Signature algorithm (refer to official demo: https://github.com/arronf2e/j...)

For example:

        var calcSignature =function(ticket,nonceStr,timeStamp,url) {
            var result = {
                jsapi_ticket: ticket,
                nonceStr: nonceStr,
                timestamp: timeStamp,
                url: url,
            }
            var str = 'jsapi_ticket=' + ticket + '&noncestr=' + nonceStr + '&timestamp=' + timeStamp + '&url=' + url;
            // sha1 signature is used for str to get signature. jsSHA module is used here. It needs install.
            shaObj = new jsSHA(str, 'TEXT');
            result.signature = shaObj.getHash('SHA-1', 'HEX');
            return result; // Back to the front end, providing the interface requested by the front end
        }
  • Next, it is returned to the front end for use (when obtaining signatures, it needs to pass url: for signature (four parameters are needed to implement signatures: timestamp, ticket, dynamic URL of front-end delivery, nonceStr) URL (dynamic) to the back end)]

Wechat Sharing

Interface Encapsulation under Axios

  • get operations, such as:

    import axios from 'axios';
    /**

    • Getting Integral Information

    • @param url

    • @returns {*}
      */

    export function getJiFenDetailInfo(url) {
    return axios.get(url).then((res)=>{

    return Promise.resolve(res);

    },(err)=>{

    return Promise.reject(err);

    });
    }

  • post operations, such as:

    import axios from 'axios';
    /**

    • Processing login

    • @param url

    • @param mobile

    • @param password

    • @returns {*}
      */

    export function dealLogin(url,mobile,password) {
    return axios.post(url,{

    mobile:mobile,
    password:password

    }).then((res)=>{

    return Promise.resolve(res);

    },(err)=>{

    return Promise.reject(err);

    });
    }

Background Management Based on VueJs

Topics: Javascript github Vue Mobile axios