使用mpvue开发小程序通用能力封装,mpvue入门

来源:未知 浏览 144次 时间 2021-06-16 01:55

MPVue 开发小程序的通用能力封装Promisify 的 wx API

import { wxp } from 'common-mpvue'; wxp.request({ ...config }).then(resp => { // do something });

import { PersistStore } from 'common-mpvue'; const store = new PersistStore({ ...storeOptions });

使用mpvue开发小程序通用能力封装

const app = getApp(); // 添加监听 app.emitter.on('event1', function() {}); // 添加一次性监听 app.emitter.once('event1', function() {}); // 移除监听 app.emitter.off('event1', listener); // 移除全部监听 app.emitter.offAll('event1');

解决了页面栈过大时无法跳转的问题网站排名请通过getApp().emitter获取这个绑定在 app 下的 emitter 实例

使用mpvue开发小程序通用能力封装

解决了页面栈过大时无法跳转的问题自动使用redirectTo替代navigateTo

const app = new App(); app.nav.navigateTo('/pages/index/index', { param1: '1' }); app.nav.navigateToH5('https://example.com'); Utilities

提供少量的实用方法

const app = getApp(); // 给url添加query参数 app.utils.addUrlQuery('/pages/index/index', { param1: '1' }); // 解析url的query为对象 app.utils.parseUrlQuery('/pages/index/index?param1=1');

提供了封装的 Request 对象适度的请求队列管理建议使用wx.httpRequest或wxp.httpRequest

wx.httpRequest.httpGet('https://example.com', { param1: '1' }); // json形式post wx.httpRequest.httpJsonPost('https://example.com', { data1: '1' }, { ...requestOptions }); // form表单形式post wx.httpRequest.httpFormPost('https://example.com', { data1: '1' }, { ...requestOptions }); // httpPost等同httpFormPost wx.httpRequest.httpPost('https://example.com', { data1: '1' }, { ...requestOptions });

为了减少重复填写配置可以重新实例化一个有固定配置的请求实例

// 配置请求携带token并以cookie形式传递 const httpRequest = wx.httpRequest .auth() .cookieToken() .form(); httpRequest.GET('https://example.com'); httpRequest.POST('https://example.com', { data1: '1' });

目前支持如下配置链

auth - 携带 token 用于鉴权auth(true)

tokenKey - 携带 token 的 keytokenKey('key')

cookieToken - 通过 cookie 携带 token

qsToken - 通过 url query 携带 token

form - 通过 form 表单形式 post

custom - 携带自定义 header 头包含设备信息等

为了将这些能力引入到 app,wx,wxp 等对象上需要按如下操作:入口 main.js

import { wrap } from 'common-mpvue'; import App from './index.vue'; wrap(App); import { WrapPage } from 'common-mpvue';

import Page from './index.vue'; new WrapPage(Page); // 或者为页面添加vuex store new WrapPage(Page, { state() { name: ''; }, mutations: { updateName(state, name) { state.name = name; } } });

标签: 携带apphttps