前段時間公司要開發個小程序的項目,因而開始了本身的小程序之旅,一切從頭看文檔開始,邊看邊作,遇到了很多坑,由於筆者一直習慣使用vue,因而就使用了mpvue框架開發;我會從構建項目開始以及開發中遇到的問題所有講述一遍,但願可以對你有幫助,或許你以爲簡單,但再簡單也是要從零走過來;在開發中有好幾個問題要注意的:html
# 全局安裝 vue-cli
$ npm install --global vue-cli
# 建立一個基於 mpvue-quickstart 模板的新項目
$ vue init mpvue/mpvue-quickstart my-project
# 安裝依賴
$ cd my-project
$ npm install
# 啓動構建
$ npm run dev
複製代碼
小程序底部的tabbar仍是很好用的,方法很簡單,在app.json中,以下:前端
小程序建立出來的裸版是不帶less、sass的,須要本身去配置:vue
小程序的頁面跳轉開發文檔上已經說的很詳細了,網址:
developers.weixin.qq.com/miniprogram…node
在此,有幾個要注意的:
(1). 若是是小程序自帶的tabbar上的頁面,在任何其它頁面跳轉到tabbar 的其中一個頁面時,要使用webpack
wx.switchTab({url : '/pages/xxx/main'})
複製代碼
(2). 關閉其它曾經打開的頁面,打開新的頁面,也就是沒有返回按鈕的,使用git
wx.reLaunch({url : '/pages/subPackages/xxx/main'})
複製代碼
(3).普通頁面的跳轉,可使用 wx.navigateTo({url: ' '})github
頁面參數的傳遞以及獲取
(1). 頁面參數的傳遞,咱們能夠經過地址欄帶過去,很簡單:web
wx.switchTab({url : '/pages/xxx/main?id=123&key=456'})
wx.switchTab({url : `/pages/xxx/main?id=${this.id}&key=${this.key}`})
複製代碼
(2). 頁面參數的獲取:
mpvue的文檔有也有說,網址:mpvue.com/mpvue/#_3算法
能夠在onLoad鉤子之後的其它鉤子中獲取,參數就在options裏,若是沒有參數,取不到時爲undefined:vue-cli
wx.onLoad(options){ console.log( options )}
wx.onShow(options){ console.log( options )}
複製代碼
若是要在其它方法中獲取,也可使用方法:
this.$root.$mp.query
複製代碼
在小程序中,咱們能夠直接使用rpx做爲單位,建議設計稿也是按照iphone6的尺寸來設計,由於rpx是按照 750px iphone6上的像素來設計的,文檔上也有說明,網址:
developers.weixin.qq.com/miniprogram…
有時咱們會使用到第三方的庫,可能它的大小不能使用rpx,這時可能就要咱們本身去換算 px 自適應了,好比echarts,它就是要你傳入單位爲px的,我就遇到了這個問題;
換算公式:
自適應尺寸 / 設備屏幕寬度 = 設計稿上元素寬度 / 設計稿寬度
也就是: 自適應尺寸 = 設計稿上元素寬度 / 設計稿寬度 * 設備屏幕寬度
例如:獲取寬度
const echartWidth = 700 / 750 * wx.getSystemInfoSync().windowWidth;
const echartHeight = 540 / 750 * wx.getSystemInfoSync().windowWidth;
複製代碼
其中,700與540是設計稿上量出來的尺寸; 750是設計稿的寬度; wx.getSystemInfoSync().windowWidth 這個方法是獲取屏幕寬度;
結果就是寬度跟高度會根據機型的不一樣會自適應,單位是px;
export default function request({
url,
data = '',
header = { 'Content-Type': 'application/json' },
method = 'GET',
dataType = 'json',
responseType = 'text',
}) {
wx.request({
url: `${baseUrl}${url}`,
method,
data,
header: header,
dataType,
responseType,
success: res => {
// 對響應進行統一處理,具體規則要與後端協調
const responseData = res.data;
if ([200].indexOf(res.statusCode) !== -1) {
response.success = responseData;
} else {
response.fail = res;
}
},
fail: error => {
response.fail = error;
},
complete() {
resolve(response.success);
},
});
}
複製代碼
import request from './request';
export function getList() {
return request({
url: '/index/hotcity',
});
}
複製代碼
import { getList} from './api'
getList().then(res => {}).catch(err => {})
複製代碼
var rotateLeft = function(lValue, iShiftBits) {
return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
};
var addUnsigned = function(lX, lY) {
var lX4, lY4, lX8, lY8, lResult;
lX8 = lX & 0x80000000;
lY8 = lY & 0x80000000;
lX4 = lX & 0x40000000;
lY4 = lY & 0x40000000;
lResult = (lX & 0x3fffffff) + (lY & 0x3fffffff);
if (lX4 & lY4) return lResult ^ 0x80000000 ^ lX8 ^ lY8;
if (lX4 | lY4) {
if (lResult & 0x40000000) return lResult ^ 0xc0000000 ^ lX8 ^ lY8;
else return lResult ^ 0x40000000 ^ lX8 ^ lY8;
} else {
return lResult ^ lX8 ^ lY8;
}
};
var F = function(x, y, z) {
return (x & y) | (~x & z);
};
var G = function(x, y, z) {
return (x & z) | (y & ~z);
};
var H = function(x, y, z) {
return x ^ y ^ z;
};
var I = function(x, y, z) {
return y ^ (x | ~z);
};
var FF = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var GG = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var HH = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var II = function(a, b, c, d, x, s, ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
};
var convertToWordArray = function(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWordsTempOne = lMessageLength + 8;
var lNumberOfWordsTempTwo =
(lNumberOfWordsTempOne - lNumberOfWordsTempOne % 64) / 64;
var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16;
var lWordArray = Array(lNumberOfWords - 1);
var lBytePosition = 0;
var lByteCount = 0;
while (lByteCount < lMessageLength) {
lWordCount = (lByteCount - lByteCount % 4) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] =
lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition);
lByteCount++;
}
lWordCount = (lByteCount - lByteCount % 4) / 4;
lBytePosition = (lByteCount % 4) * 8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition);
lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
return lWordArray;
};
var wordToHex = function(lValue) {
var WordToHexValue = '',
WordToHexValueTemp = '',
lByte,
lCount;
for (lCount = 0; lCount <= 3; lCount++) {
lByte = (lValue >>> (lCount * 8)) & 255;
WordToHexValueTemp = '0' + lByte.toString(16);
WordToHexValue =
WordToHexValue +
WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2);
}
return WordToHexValue;
};
var uTF8Encode = function(string) {
string = string.replace(/\x0d\x0a/g, '\x0a');
var output = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
output += String.fromCharCode(c);
} else if (c > 127 && c < 2048) {
output += String.fromCharCode((c >> 6) | 192);
output += String.fromCharCode((c & 63) | 128);
} else {
output += String.fromCharCode((c >> 12) | 224);
output += String.fromCharCode(((c >> 6) & 63) | 128);
output += String.fromCharCode((c & 63) | 128);
}
}
return output;
};
function md5(string) {
var x = Array();
var k, AA, BB, CC, DD, a, b, c, d;
var S11 = 7,
S12 = 12,
S13 = 17,
S14 = 22;
var S21 = 5,
S22 = 9,
S23 = 14,
S24 = 20;
var S31 = 4,
S32 = 11,
S33 = 16,
S34 = 23;
var S41 = 6,
S42 = 10,
S43 = 15,
S44 = 21;
string = uTF8Encode(string);
x = convertToWordArray(string);
a = 0x67452301;
b = 0xefcdab89;
c = 0x98badcfe;
d = 0x10325476;
for (k = 0; k < x.length; k += 16) {
AA = a;
BB = b;
CC = c;
DD = d;
a = FF(a, b, c, d, x[k + 0], S11, 0xd76aa478);
d = FF(d, a, b, c, x[k + 1], S12, 0xe8c7b756);
c = FF(c, d, a, b, x[k + 2], S13, 0x242070db);
b = FF(b, c, d, a, x[k + 3], S14, 0xc1bdceee);
a = FF(a, b, c, d, x[k + 4], S11, 0xf57c0faf);
d = FF(d, a, b, c, x[k + 5], S12, 0x4787c62a);
c = FF(c, d, a, b, x[k + 6], S13, 0xa8304613);
b = FF(b, c, d, a, x[k + 7], S14, 0xfd469501);
a = FF(a, b, c, d, x[k + 8], S11, 0x698098d8);
d = FF(d, a, b, c, x[k + 9], S12, 0x8b44f7af);
c = FF(c, d, a, b, x[k + 10], S13, 0xffff5bb1);
b = FF(b, c, d, a, x[k + 11], S14, 0x895cd7be);
a = FF(a, b, c, d, x[k + 12], S11, 0x6b901122);
d = FF(d, a, b, c, x[k + 13], S12, 0xfd987193);
c = FF(c, d, a, b, x[k + 14], S13, 0xa679438e);
b = FF(b, c, d, a, x[k + 15], S14, 0x49b40821);
a = GG(a, b, c, d, x[k + 1], S21, 0xf61e2562);
d = GG(d, a, b, c, x[k + 6], S22, 0xc040b340);
c = GG(c, d, a, b, x[k + 11], S23, 0x265e5a51);
b = GG(b, c, d, a, x[k + 0], S24, 0xe9b6c7aa);
a = GG(a, b, c, d, x[k + 5], S21, 0xd62f105d);
d = GG(d, a, b, c, x[k + 10], S22, 0x2441453);
c = GG(c, d, a, b, x[k + 15], S23, 0xd8a1e681);
b = GG(b, c, d, a, x[k + 4], S24, 0xe7d3fbc8);
a = GG(a, b, c, d, x[k + 9], S21, 0x21e1cde6);
d = GG(d, a, b, c, x[k + 14], S22, 0xc33707d6);
c = GG(c, d, a, b, x[k + 3], S23, 0xf4d50d87);
b = GG(b, c, d, a, x[k + 8], S24, 0x455a14ed);
a = GG(a, b, c, d, x[k + 13], S21, 0xa9e3e905);
d = GG(d, a, b, c, x[k + 2], S22, 0xfcefa3f8);
c = GG(c, d, a, b, x[k + 7], S23, 0x676f02d9);
b = GG(b, c, d, a, x[k + 12], S24, 0x8d2a4c8a);
a = HH(a, b, c, d, x[k + 5], S31, 0xfffa3942);
d = HH(d, a, b, c, x[k + 8], S32, 0x8771f681);
c = HH(c, d, a, b, x[k + 11], S33, 0x6d9d6122);
b = HH(b, c, d, a, x[k + 14], S34, 0xfde5380c);
a = HH(a, b, c, d, x[k + 1], S31, 0xa4beea44);
d = HH(d, a, b, c, x[k + 4], S32, 0x4bdecfa9);
c = HH(c, d, a, b, x[k + 7], S33, 0xf6bb4b60);
b = HH(b, c, d, a, x[k + 10], S34, 0xbebfbc70);
a = HH(a, b, c, d, x[k + 13], S31, 0x289b7ec6);
d = HH(d, a, b, c, x[k + 0], S32, 0xeaa127fa);
c = HH(c, d, a, b, x[k + 3], S33, 0xd4ef3085);
b = HH(b, c, d, a, x[k + 6], S34, 0x4881d05);
a = HH(a, b, c, d, x[k + 9], S31, 0xd9d4d039);
d = HH(d, a, b, c, x[k + 12], S32, 0xe6db99e5);
c = HH(c, d, a, b, x[k + 15], S33, 0x1fa27cf8);
b = HH(b, c, d, a, x[k + 2], S34, 0xc4ac5665);
a = II(a, b, c, d, x[k + 0], S41, 0xf4292244);
d = II(d, a, b, c, x[k + 7], S42, 0x432aff97);
c = II(c, d, a, b, x[k + 14], S43, 0xab9423a7);
b = II(b, c, d, a, x[k + 5], S44, 0xfc93a039);
a = II(a, b, c, d, x[k + 12], S41, 0x655b59c3);
d = II(d, a, b, c, x[k + 3], S42, 0x8f0ccc92);
c = II(c, d, a, b, x[k + 10], S43, 0xffeff47d);
b = II(b, c, d, a, x[k + 1], S44, 0x85845dd1);
a = II(a, b, c, d, x[k + 8], S41, 0x6fa87e4f);
d = II(d, a, b, c, x[k + 15], S42, 0xfe2ce6e0);
c = II(c, d, a, b, x[k + 6], S43, 0xa3014314);
b = II(b, c, d, a, x[k + 13], S44, 0x4e0811a1);
a = II(a, b, c, d, x[k + 4], S41, 0xf7537e82);
d = II(d, a, b, c, x[k + 11], S42, 0xbd3af235);
c = II(c, d, a, b, x[k + 2], S43, 0x2ad7d2bb);
b = II(b, c, d, a, x[k + 9], S44, 0xeb86d391);
a = addUnsigned(a, AA);
b = addUnsigned(b, BB);
c = addUnsigned(c, CC);
d = addUnsigned(d, DD);
}
var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d);
return tempValue.toLowerCase();
}
export default md5;
複製代碼
import md5 from '@/utils/md5';
md5('要加密的字符串');
複製代碼
export function joinParams(obj) {
let str = '';
const keys = Object.keys(obj);
const values = Object.values(obj);
keys.forEach((item, index, arr) => {
str +=
arr.length - 1 === index
? `${item}=${values[index]}`
: `${item}=${values[index]}&`;
});
return str;
}
複製代碼
import { randomString, joinParams } from '@/utils';
const key = prk;
const nonce = randomString(4);
const timestamp = new Date().getTime();
joinParams({ key, nonce, timestamp })
複製代碼
export function randomString(
length,
chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
) {
let result = '';
for (let i = length; i > 0; i -= 1)
result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
複製代碼
import { randomString } from '@/utils';
const nonce = randomString(4);
複製代碼
Object.assign(this.$data, this.$options.data());
複製代碼
onShow(){
Object.assign(this.$data, this.$options.data());
}
onHide(){
Object.assign(this.$data, this.$options.data());
}
複製代碼
wx.checkSession({
success: () => {
console.log('受權狀態,能夠去獲取token,若是沒有token,說明沒有登陸,仍是要去受權登陸 ')
},
fail: () => {
console.log('沒有受權,能夠跳轉到登陸頁面')
}
})
複製代碼
// 注意:安卓與IOS獲取回來的路徑不同,在使用mp-vue時
// 在安卓中
const list = [
'pages/subPackages/cardDetail/main',
'pages/subPackages/invitationRegister/main',
];
// 在IOS中, 在頭部多一個"/"
const list = [
'/pages/subPackages/cardDetail/main',
'/pages/subPackages/invitationRegister/main',
];
// 因此引用時要作一下判斷系統的判斷,這裏就不詳細講了
export function permission(val, callback) {
if (list.indexOf(val) === -1) {
callback();
}
}
複製代碼
// 在app.vue頁面中
import { permission } from '@/permission/index.js';
onShow() {
this.checkLogin();
},
methods: {
checkLogin() {
// 獲取當前頁面的路徑 this.$root.$mp.appOptions.path;
const path = this.$root.$mp.appOptions.path;
permission(path, () => {
// 執行檢測代碼
wx.checkSession({
success: () => {
console.log('受權狀態,能夠去獲取token,若是沒有token,說明沒有登陸,仍是要去受權登陸 ')
},
fail: () => {
console.log('沒有受權,能夠跳轉到登陸頁面')
}
})
});
},
},
複製代碼
<button
open-type="getUserInfo"
@getuserinfo="toAuth"
class="button_auth">受權登陸</button>
methods:{
toAuth(){
let code = '';
// 一、獲取code
wx.login({
success: res => {
if (res.code) {
code = res.code;
// 二、獲取判斷用戶是否受權
wx.getSetting({
success: res1 => {
// 用戶已受權,會自動執行此處
if (res1.authSetting['scope.userInfo']) {
wx.showLoading({
title: '受權中...',
});
// 三、獲取用戶信息
wx.getUserInfo({
success: res2 => {
console.log(res2) // 用戶信息,二次請求解密用的,傳給後臺,前端也能夠作二次請求
},
});
} else {
// 用戶沒有受權,須要受權,從新拉起受權
wx.authorize({
scope: 'scope.userInfo',
});
}
},
fail: () => {
},
});
}
},
fail: () => {
// console.log(err);
},
});
}
}
複製代碼
// 二次驗證獲取successkey/open_id
wx.request({
url: "https://api.weixin.qq.com/sns/jscode2session",
header: { "Content-Type": "application/json" },
method: "GET",
data: {
appid: "", // 開發平臺上的appid
secret: "", // 開發平臺上的secret
js_code: code, // 第一步獲取到的code
grant_type: "authorization_code" // 這個是官方要求固定的
},
success: e => {
e.data.session_key // session_key就是解密要用到的key
}
});
複製代碼
var WXBizDataCrypt = require('./WXBizDataCrypt')
let appId = 'wx168b9fc4343434434'
// var sessionKey = wx.getStorageSync("openId_key").session_key
const encryptedData =
'CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM'+
'QmRzooG2xrDcvSnxIMXFufNstNGTyaGS'+
'9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+'+
'3hVbJSRgv+4lGOETKUQz6OYStslQ142d'+
'NCuabNPGBzlooOmB231qMM85d2/fV6Ch'+
'evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6'+
'/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw'+
'u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn'+
'/Hz7saL8xz+W//FRAUid1OksQaQx4CMs'+
'8LOddcQhULW4ucetDf96JcR3g0gfRK4P'+
'C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB'+
'6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns'+
'/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd'+
'lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV'+
'oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG'+
'20f0a04COwfneQAGGwd5oa+T8yO5hzuy'+
'Db/XcxxmK01EpqOyuxINew=='
// var pc = new WXBizDataCrypt(appId, sessionKey)
// var data = pc.decryptData(encryptedData , iv)
// console.log('解密後 data: ', data)
const decode = (sessionKey,encryptedData,iv) => {
let pc = new WXBizDataCrypt(appId, sessionKey)
let data = pc.decryptData(encryptedData , iv)
// 獲取到的用戶信息,能夠存起來
wx.setStorage({
key:"openId",
data:data.openId
})
console.log(data);
}
export default decode
複製代碼
import decode from "@/utils/node_decode/decode.js";
decode(
e.data.session_key,
userinfo.encryptedData,
userinfo.iv
);
複製代碼
HTML:
<cover-view
class="text-2"
@click="saveQrcode"
>保存到手機相冊</cover-view>
<canvas
canvas-id="saveCanvasId"
class="canvas-style"
style="width:200px;height:200px"
></canvas>
JS:
data:{
return{
isShowAuthSaveImg: true
}
}
methods:
saveQrcode() {
if (this.isShowAuthSaveImg) {
let that = this;
wx.getImageInfo({
src: this.qrCodeSrc,
success: e => {
const ctx = wx.createCanvasContext("saveCanvasId");
ctx.drawImage(e.path, 0, 0, 200, 200);
ctx.draw(false, that.drawCallback());
}
});
} else {
wx.openSetting({
success: e => {
if (e.authSetting["scope.writePhotosAlbum"]) {
this.isShowAuthSaveImg = true;
}
}
});
}
},
drawCallback() {
setTimeout(() => {
wx.canvasToTempFilePath({
canvasId: "saveCanvasId",
fileType: "png",
x: 0,
y: 0,
success: res => {
wx.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: e => {
this.onShowDownLoadImg = false;
},
fail: e => {
wx.getSetting({
success: e => {
if (!e.authSetting["scope.writePhotosAlbum"]) {
this.isShowAuthSaveImg = false;
}
}
});
}
});
}
});
}, 1000);
},
複製代碼
2、圖片內容有動態數據填充:HTML:
<button
class="picture_share"
:open-type="openTypebt"
@click="pictureShare"
plain="true"
>圖片分享</button>
JS:
data:{
retun{
openTypebt: '',
}
},
onShow() {
wx.getSetting({
success: res => {
if (res.authSetting['scope.writePhotosAlbum']) {
this.openTypebt = '';
}
},
});
},
methods:{
pictureShare() {
wx.showLoading({
title: '圖片保存中...',
});
wx.downloadFile({ // 文件下載到本地
url: `${baseUrl}/view/screenShot?url=${
this.hunterInfoData.view_url
}&with=540&height=1350`, // 圖片在後端的地址
header: headers, // 後端要求的請求頭
success: e => {
if (e.statusCode === 500) {
wx.hideLoading();
$Toast({
content: '服務器繁忙,稍候重試',
type: 'warning',
});
return;
}
wx.saveImageToPhotosAlbum({ // 調用保存圖片方法
filePath: e.tempFilePath, // 圖片的臨時路徑
success: () => {
wx.hideLoading();
$Toast({
content: '圖片保存成功',
type: 'success',
});
},
fail: () => { // 用戶拒絕,在這個回調中將type設爲
// openSetting,下次再點時調起受權
wx.hideLoading();
wx.getSetting({
success: res => {
if (!res.authSetting['scope.writePhotosAlbum']) {
this.openTypebt = 'openSetting';
}
},
});
},
});
},
});
},
}
複製代碼
<template>
<div class="web_view">
<web-view :src="url"></web-view>
</div>
</template>
<script>
export default {
name: 'WebView',
data() {
return {
url: '',
};
},
onShow() {
this.setTitle();
},
methods: {
setTitle() {
this.url = this.$root.$mp.query.url;
wx.setNavigationBarTitle({ // 動態設置標題
title: this.$root.$mp.query.title,
});
},
},
};
</script>
<style lang="less">
</style>
複製代碼
button::after {
border-radius: none;
border: none;
}
複製代碼
wx.setNavigationBarTitle({
title: '標題欄',
});
複製代碼
<div :style="styleObj"></div>
data:{
return{
styleObj:{
color: '#fff'
}
}
}
複製代碼
不過咱們可能經過computed將對象轉換成字符串就能夠解決問題:<div :style="btnStyle"></div>
data:{
return{
style: {
width: '690rpx',
height: '88rpx',
'background-color': '#09bb07',
'border-radius': '10rpx',
'line-height': '88rpx',
'text-align': 'center',
color: '#ffffff',
'font-size': '36rpx',
margin: '57rpx auto',
},
}
}
computed:{
btnStyle(){
let s = ''
let arr = []
for(let i in this.style){
arr.push(i+':'+this.style[i]);
}
s = arr.join(';')
return s
}
}
複製代碼
onLoad(options) {
// options 中的 scene 須要使用 decodeURIComponent
// 才能獲取到生成二維碼時傳入的 scene
Object.assign(this.$data, this.$options.data());
if (JSON.stringify(options) !== '{}') {
const scene = decodeURIComponent(options.q);
console.log(scene)
// 截取參數
this.code = scene.substring(scene.indexOf('code=') + 5);
}
},
複製代碼
使用圖表,必然會想到百度的echarts,但它的體積驚人,嚇得趕忙喝了兩口水壓壓驚;不可能將整個包下載下來使用,隨便都超過2M沒法打包,咱們能夠到echarts的官網上去定製本身要用到的,並且要壓縮版的,而後由於咱們使用mpvue,因此這裏能夠引入mpvue-echarts來開發,下面就來說下如何使用: 具體步驟:
npm install mpvue-charts --save
複製代碼
import mpvueEcharts from 'mpvue-echarts';
import * as echarts from '../../../static/echarts.min .js';
複製代碼
注意:echarts的路徑根據實際的文件位置引入;components: {
mpvueEcharts
},
複製代碼
<mpvue-echarts
:echarts="echarts"
:on-init="initChart" ></mpvue-echarts>
複製代碼
data() {
return {
echarts, // echarts定製組件
// 橫軸數據
AxisXData: [],
// 圖表動態數據
echartsData: [],
};
}
複製代碼
methods:{
// 圖表
initChart(canvas) {
let chart = null;
// 動態獲取圖表寬度
const echartWidth = 700 / 750 * wx.getSystemInfoSync().windowWidth;
// 動態獲取圖表高度
const echartHeight = 540 / 750 * wx.getSystemInfoSync().windowWidth;
chart = echarts.init(canvas, null, {
width: echartWidth,
height: echartHeight,
});
canvas.setChart(chart);
const option = {
// 橫軸配置
xAxis: {
type: 'category',
data: this.AxisXData,
axisLabel: {
interval: 0,
fontSize: 12,
},
splitLine: {
show: true,
lineStyle: {
color: '#f2f2f2',
},
},
axisTick: {
show: false,
},
axisLine: {
lineStyle: {
color: '#3488ea',
width: 2,
},
},
},
// 縱軸配置
yAxis: {
// 縱軸標尺固定
type: 'value',
scale: true,
name: '簡歷數',
nameGap: 15,
max: 100,
min: 0,
boundaryGap: [0.2, 0.2],
splitLine: {
show: true,
lineStyle: {
color: '#f2f2f2',
},
},
axisTick: {
show: false,
},
axisLine: {
lineStyle: {
color: '#3488ea',
width: 2,
},
},
},
// 圖表類型及填充數據
series: [
{
data: [{value:20},{value:40}],
type: 'bar',
itemStyle: {
color: '#3488ea',
},
barWidth: 20,
},
],
grid: {
left: '6%',
right: '0',
// bottom: '0',
top: '30',
containLabel: true,
},
};
chart.setOption(option);
return chart; // 返回 chart 後能夠自動綁定觸摸操做
},
}
複製代碼
data(){
return{
img_1: "/static/images/xxx.png",
img_2: require('../../../static/images/xxx.png')
}
}
複製代碼
2、到webpack.base.conf.js配置裏將圖片限制大小改大:{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 1000000000, // 這裏改大點
name: utils.assetsPath('img/[name].[ext]'),
},
},
複製代碼
wx.showLoading({
success: () => { // 這樣就能夠了
this.data = 123
}
})
複製代碼
{
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark", // 配置小圓點顏色
}
複製代碼
onPullDownRefresh() {
wx.showLoading({
title: '加載中...',
});
// 請求數據
},
複製代碼
wx.stopPullDownRefresh();
複製代碼
wx.getSystemInfoSync().windowHeight
複製代碼
wx.createSelectorQuery().selectAll(val).boundingClientRect(rects =>{
console.log(rects) // rects是所選的元素屬性,包括寬、高等等
})
複製代碼
export function scrollHeight(val, callback) {
let clientHeight = 0;
// 獲取屏幕高度與寬度
try {
const res = wx.getSystemInfoSync();
clientHeight = res.windowHeight;
} catch (e) {
// Do something when catch error
}
setTimeout(() => {
let allHeight = 0;
wx
.createSelectorQuery()
.selectAll(val)
.boundingClientRect(rects => {
rects.forEach(rect => {
allHeight += rect.height;
});
if (allHeight) {
callback(`${clientHeight - allHeight}px`);
} else {
wx
.createSelectorQuery()
.selectAll(val)
.boundingClientRect(res => {
res.forEach(rec => {
allHeight += rec.height;
});
callback(`${clientHeight - allHeight}px`);
});
}
})
.exec();
}, 400);
}
複製代碼
import { scrollHeight } from '@/你的文件名';
data(){
return {
height: 0
}
}
methods:{
// 動態獲取sroll-view高度
getScrollHeight() {
scrollHeight('.carousel_wrap,.send_tab',this.scrollCallBack);
},
scrollCallBack(val) {
this.height = val;
},
}
複製代碼
<scroll-view
@scrolltolower="觸底的事件,用來請求下一頁數據"
scroll-y
:style="{height:scrollHeight,overFlow:'hidden'}"
v-if="height"
scroll-top="0"
>
<ul>
<li></li>
</ul>
</scroll-view>
複製代碼
<button open-type="share"></button>
onShareAppMessage() {
return {
title: '分享頁面名字',
path: `分享頁面路徑`, // 如 '/pages/xxx/main'
imageUrl: '圖片路徑,不能網絡圖片', // 如:'/static/images/xxx.jpg'
};
},
複製代碼
// 其中 report-submit="true" 表示是否返回formid
<form
report-submit="true"
@submit="bindSubmit">
// 表單
</form>
methods:{
bindSubmit(e) {
console.log( e.mp.detail.formId);
},
}
複製代碼
<img src="" mode="widthFix" width="200"/>
複製代碼
npm install weapp-qrcode --save
複製代碼
import drawQrcode from "weapp-qrcode";
HTML:
<canvas canvas-id="saveCanvasId" ></canvas>
methods:{
getQrcode(){
drawQrcode({
width: width,
height: height,
canvasId: canvasId,
text: text,
correctLevel:3,
typeNumber:8,
callback: () => {
// 將畫布中的元素轉成圖片臨時路徑
wx.canvasToTempFilePath({
canvasId: canvasId,
fileType:"png",
x:0,
y:0,
success(res) {
console.log(res); // 獲得圖片路徑,能夠展現
}
})
}
})
}
}
複製代碼
npm install iview-weapp --save-dev
複製代碼
<div>
<i-toast id="toast"/>
</div>
複製代碼
import { $Toast } from '../../../static/iview/base/index.js';
複製代碼
$Toast({
content: '此內容必填',
type: 'warning',
});
複製代碼