VueJs项目笔记

======================知识点总结===========================

一、keep-alive(完成页面的缓存)

二、 挪动端牢固定位的处置惩罚方案

三、 Vue表单校验

横向滑动的tab选项卡,以及输入法定位相干的

  • JQ插件网http://jq22.com
  • 当第一个输入框自动取得光标的时刻,弹出的输入法会把规划顶上去

题目1:能够摆布滑动的tab

  • 将项目中引入Jq框架和tab插件

当第一个输入框自动取得光标的时刻,弹出的输入法会把规划顶上去?

  • 给最外层盒子加上相对定位,而且设置牢固高度

     .reg-layer {
       width: 100%;
       height: 360px;
       background: #ffffff;
       position: absolute;
       left: 0;
       top: 0;
       bottom: 0;
       right: 0;
     }
  • 再给登录框设置牢固

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

怎样去加载一倍图,二倍图,三倍图等

  • 运用Retina.js

上拉革新、下拉加载更多

登录注册

  • VueJs保留token
  • 推断token失效

VueJs保留token

Vue-cli proxyTable 处置惩罚开辟环境的跨域题目

运用localStorage处置惩罚vuex在页面革新后数据被消灭的题目

如安在vue中完成路由跳转推断用户权限功用?

Axios

Ju Network Status By JS

Web App Notes

Axios WebSite Address

No NetWork SPA

VueJS Communication among brothers

webpack多页运用架构系列

Vue-Cli设置文件剖析

下拉革新

Vue-Cli打包宣布

挪动端-webkit-user-select:none致使input/textarea输入框没法输入

VueJs推断Token逾期

Axios中的delete要求

VueJs挪动端图片紧缩上传

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

微信民众号

UpLoad File In VueJs

Show PDF In Broswer

Show PDF In Broswer Code

  • http://localhost:63342/pdf.js-gh-pages/examples/index.html?_ijt=s4h3uipnnk8bec8b1ddn82mqnn
  • 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

PDF.js怎样一次性的加载完一切的pdf的内容

在举行文件(pdf、word)等的上传中,怎样辨别?

  • http://blog.csdn.net/shenshen…
  • article/details/21626315
  • accept=”application/msexcel” —-对应上传excel
  • accept=”application/msword” —-对应上传word
  • accept=”application/pdf” —-对应上传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>
  //加载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('下一页的数据');
      }
    },
    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;
//需要加载的pdf的文件
// 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);
      }
    });
  },
  /**
   * 设置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防备页面涌现闪灼的状况

处置惩罚TextArea自动随文本高度自适应高度

PC端与挪动端中option的宽度题目

搜刮规划的题目—-子组件去处置惩罚

  • 路由切换(tab切换)完成差别的规划

VueJs NextTick的妙用

回到本来的转动位置以及回到顶部(待完美)

  • 当路处于脱离状况的时刻,存储转动的位置
  • 当路由处于进入状况的时刻,掏出转动位置举行推断,来显现或隐蔽“返回顶部”的按钮

VueJs自动化测试

Web App中一行笔墨显现不下,左侧用…示意

革新当前页面

  • this.$router.go(0);

VueJs打包优化

WebPack中静态资本url的设置

Vue-Cli webpack设置

挪动端富文本框的集成

Vue-Router中push与replace的区分与联络

VueJs富文本框(发帖功用)

div设置了contentEditable属性。android上平常,IOS上涌现题目

  • 运用div来模仿input或许textarea来举行内容输入的操纵,完成富文本框的功用
  • 遇到题目

    到场style=”-webkit-user-select: auto”就可以涌现光标和编辑了

Vuejs-Cordova-Framework-Webapp

Css-Scroller(效果图,暂时不用在项目中)

Scroll开源库完成列表转动动画

H5掌握制止横屏

文件上传(do not)

window.open被阻拦题目(完成)

  • 经由过程借用a标签并发生随机的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);
                  // 防备反复增加
                  if(!document.getElementById(id)) {
                    document.body.appendChild(a);
                  }
                  a.click();
                },

`

  • 挪用

    this.newWin(localStorage.getItem(‘url’),”dow”,”csa”+this.JsGuid());

log东西类(便于在开辟过程当中举行调试打印),在上线后将一切log信息隐蔽

  • code

    /**

    • Created by THINK on 2017/7/3.
    • 日记东西类:开辟阶段将flag设置为true(能够瞥见log),上线后将flag设置为false(看不见log)
    • @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

修复上拉革新,下拉加载

  • vue-scroller(自动地去举行了加载更多(bug))

对项目举行优化性的操纵

  • 代码复用
  • 资本的处置惩罚

安卓模仿器测试

  • 装置题目:进入Bios体系设置硬件假造化

假造化手艺的能够在BIOS中开启,开启要领以下:

  1、进入BIOS。开机时按F2或F12或DEL或ESC等键(各电脑有所差别)。
  2、进入BIOS后,找到Configuration选项,挑选Intel Virtual Technology并回车,将光标移至Enabled,然后再回车,末了按F10保留并退出。
  假如找不到Configuration选项,能够尝尝下面的要领:
  (1)某些HP(惠普)电脑进入BIOS后,需要挑选SystemConfiguration(体系设置)菜单,然后挑选Device Configuration(装备设置),找到Virtualization Technology,设置为Enabled。
  (2)某些遐想Thinkpad电脑进入BIOS后,需要挑选Security菜单,然后挑选Virtualization,设置为Enabled。
  (3)某些DELL(戴尔)电脑进入BIOS后,需要挑选Processor Settings菜单,然后挑选VirtualizationTechnology,设置为Enabled。
  假造化在1960年为了形貌假造机(实验性的IBM M44/44X体系)这个观点被第一次提出。对假造机的架设和治理被称为平台假造化,如今也被称为服务器假造化。

将营业逻辑代码与三方代码离开举行打包

  • 在entry入口中设置,如星散jQuery
  • 运用vue-cli打包后默许临盆三个js文件

    • app.43fcdsfcafds.js:项目中你编写的营业逻辑的代码
    • vender.20deewdew32eed.js:经由过程npm install下载依靠的js,css代码(node_modules目录下)
    • manifest.4cbcd0f5d52237fb29b0.js:缓存检测文件,每次打包,经由过程该文件举行版本的检测
  • 将临盆环境与开辟环境中的资本打包运用

vender:3.34m app:1.26m,怎样去削减它们的体积

  • vender.xsaxsxx.js.map文件的作用

source map文件是js文件紧缩后,文件的变量名替代对应、变量所在位置等元信息数据文件,平常这类文件和min.js主文件放在同一个目录下。 比方紧缩后原变量是map,紧缩后经由过程变量替代划定规矩能够会被替代成a,这时候source map文件会记录下这个mapping的信息,如许的优点就是说,在调试的时刻,假如有一些JS报错,那末浏览器会经由过程剖析这个map文件来从新merge紧缩后的js,使开辟者能够用未紧缩前的代码来调试,如许会给我们带来很大的轻易!

文件的按需加载(搞定)—项目优化的一大步

  • 依据vue的路由去按需加载组件

  • vue组件的按需加载:处置惩罚了打包事后app.xscs3243rcds.js文件过大的瑕玷
  • 进一步优化(三方不太动的js文件,经由过程cdn去加载)
  • 援用雷同的模块,打包后涌现反复的资本,将三方的零丁举行打包

WebPack代码支解

WebPack中文网

VueJs Seo(Nuxt.js)

WeChat微信分享

Vue-Cli中引入weixin-js-sdk

     isWeiXin(){
        //推断是不是是微信浏览器
        let ua = window.navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) === 'micromessenger') {
          return true;
        } else {
          return false;
        }
      },
  • 分享完成流程

    • ①装置微信sdk npm install weixin-js-sdk –save-dev
    • ②经由过程import或许require的体式格局将其引入到需要的组件中
    • ③猎取署名相干的信息
    • ④经由过程config接口注入权限考证设置

       wx.config({
      debug: true, 
      appId: '', // 必填,民众号的唯一标识
      timestamp: , // 必填,天生署名的时候戳
      nonceStr: '', // 必填,天生署名的随机串
      signature: '',// 必填,署名,见附录1
      jsApiList: [] // 必填,需要运用的JS接口列表,一切JS接口列表见附录2
      });
      
    • ⑤经由过程ready接口处置惩罚胜利考证

          wx.ready(function(){
      // config信息考证后会实行ready要领,一切接口挪用都必需在config接口取得效果以后,config是一个客户端的异步操纵,所以假如需要在页面加载时就挪用相干接口,则须把相干接口放在ready函数中挪用来确保准确实行。关于用户触发时才挪用的接口,则能够直接挪用,不需要放在ready函数中。
              //举行分享的操纵
               //分享到朋侪圈
                wx.onMenuShareTimeline({
                  title: '测试信息', // 分享题目
                  link: '', // 分享链接,该链接域名或途径必需与当前页面对应的民众号JS平安域名一致
                  imgUrl: '', // 分享图标
                  success: function (res) {
                    // 用户确认分享后实行的回调函数
                    logUtil.printLog("分享到朋侪圈胜利返回的信息为:",res);
                  },
                  cancel: function (res) {
                    // 用户作废分享后实行的回调函数
                    logUtil.printLog("作废分享到朋侪圈返回的信息为:",res);
                  }
                });
                //分享给朋侪
                wx.onMenuShareAppMessage({
                  title: '', // 分享题目
                  desc: '', // 分享形貌
                  link: '', // 分享链接,该链接域名或途径必需与当前页面对应的民众号JS平安域名一致
                  imgUrl: '', // 分享图标
                  type: '', // 分享范例,music、video或link,不填默许为link
                  dataUrl: '', // 假如type是music或video,则要供应数据链接,默许为空
                  success: function (res) {
                    // 用户确认分享后实行的回调函数
                    logUtil.printLog("分享给朋侪胜利返回的信息为:",res);
                  },
                  cancel: function (res) {
                    // 用户作废分享后实行的回调函数
                    logUtil.printLog("作废分享给朋侪返回的信息为:",res);
                  }
                });
                //分享到QQ
                wx.onMenuShareQQ({
                  title: '', // 分享题目
                  desc: '', // 分享形貌
                  link: '', // 分享链接
                  imgUrl: '', // 分享图标
                  success: function (res) {
                    // 用户确认分享后实行的回调函数
                    logUtil.printLog("分享到QQ挚友胜利返回的信息为:",res);
                  },
                  cancel: function (res) {
                    // 用户作废分享后实行的回调函数
                    logUtil.printLog("作废分享给QQ挚友返回的信息为:",res);
                  }
                });
                //分享到QQ空间
                wx.onMenuShareQZone({
                  title: '', // 分享题目
                  desc: '', // 分享形貌
                  link: '', // 分享链接
                  imgUrl: '', // 分享图标
                  success: function (res) {
                    // 用户确认分享后实行的回调函数
                    logUtil.printLog("分享到QQ空间胜利返回的信息为:",res);
                  },
                  cancel: function (res) {
                    // 用户作废分享后实行的回调函数
                    logUtil.printLog("作废分享到QQ空间返回的信息为:",res);
                  }
                });
      });
      
    • ⑥经由过程error接口处置惩罚失利考证

      • wx.error(function(res){
// config信息考证失利会实行error函数,如署名逾期致使考证失利,详细错误信息能够翻开config的debug形式检察,也能够在返回的res参数中检察,关于SPA能够在这里更新署名。
});    
  • 署名由:noncestr(署名随机字符串,随意写)、jsapi_ticket(单子)、timestamp(时候戳)、url(必需悉数小写)等构成
  • 猎取access_token

    要求接口:https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的secret
    要求要领: get
    返回效果: access_token (有效期7200秒,必需在服务端缓存) 
  • 猎取单子jsapi_ticket

    要求接口:https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=上一步中猎取的access_token&type=jsapi
    要求要领: get,
    type: JSON,
    返回效果: jsapi_ticket (有效期7200秒,必需在服务端缓存)
  • 天生时候戳(timestamp)

    // 时候戳发生函数
    var timeStamp = function () {
        return parseInt(new Date().getTime() / 1000) + '';
    };
    
  • 署名算法(能够参考官方给出的demo:https://github.com/arronf2e/j…

比方:

        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;
            // 对str运用sha1署名,获得signature,这里运用jsSHA模块,需install
            shaObj = new jsSHA(str, 'TEXT');
            result.signature = shaObj.getHash('SHA-1', 'HEX');
            return result; // 返回到前端,供应接口由前端要求
        }
  • 接下来就返回给前端运用(在猎取署名的时刻需要通报url:用于署名的(需要四个参数来完成署名:时候戳、ticket、前端通报的动态的url、nonceStr) url(动态的)给后端)]

微信分享

Axios下的接口封装

  • get操纵,如:
import axios from 'axios';
        /**
         * 猎取积分信息
         * @param url
         * @returns {*}
         */
        export function getJiFenDetailInfo(url) {
          return axios.get(url).then((res)=>{
            return Promise.resolve(res);
          },(err)=>{
            return Promise.reject(err);
          });
        }
  • post操纵,如:
 import axios from 'axios';
        /**
         * 处置惩罚登录
         * @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);
          });
        }

基于VueJs的背景治理

挪动端html2canvas天生图片转换为File对象兼容处置惩罚

触及点:Base64转换为file对象

 /**
       * 将Base64转换为file对象
       * @param dataurl:文件的base64示意
       * @param filename:文件名
       * @return {File}:返回的file对象
       */
      dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type:mime});
      },

发明ios低版本涌现了兼容题目,终究发明题目出在new File()这里。那末就得想其他处置惩罚办法了,能够先将Base64举行二进制转换操纵,终究将二进制转换为File对象就可以够处置惩罚。

 /**
       * 将base64先转换为二进制对象
       * */
      dataURLtoBlob(dataurl) {
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },
      /**
       * 末了再将二进制转换为file对象
       * */
      blobToFile(theBlob, fileName){
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
      },

it is done!

    原文作者:darkCode
    原文地址: https://segmentfault.com/a/1190000010191885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞