小程序 vant 項目記錄總結 使用 scss 分享 訂閱消息 wxs 分包 echarts圖表 canvas getCurrentPages頁面棧

小程序 + vant

vant

下載

npm init -ynpm i @vant/weapp -S --production

修改 app.json

將 app.json 中的 “style”: “v2” 去除

修改 project.config.json

{..."setting": {..."packNpmManually": true,"packNpmRelationList": [{"packageJsonPath": "./package.json","miniprogramNpmDistDir": "./"}]}
}

構建 npm 包

打開微信開發者工具,點擊 工具 -> 構建 npm,并勾選 使用 npm 模塊 選項,構建完成后,即可引入組件。

van-dialog

before-close 回調函數使用
不需要 confirm,cancel 事件

<van-dialog use-slot show="{{ show }}" before-close="{{ beforeClose }}"></van-dialog>
Page({onLoad() {this.setData({beforeClose: (action) => this.confirmScore(action),});},confirmScore(action) {return new Promise((resolve, reject) => {if (action === "cancel") return resolve(true);if (action === "confirm") {if (...) return resolve(false);return resolve(true);}});},
})

小程序

使用 typescript、less、sass

編譯插件配置,目前支持編譯插件有 typescript、less、sass
project.config.json

{"setting": {"useCompilerPlugins": ["typescript","sass"]}
}

表示項目支持直接使用 typescript 和 sass

.wxss 文件命名 .scss

setData 多種賦值寫法

const index = 0;data: {list: [{page: 1,limit: 10,data: [],finished: false,},],obj: {name:'ls',},name: 'ls'
},
this.setData({name: 'xr',obj: {},'obj.name': 'xr','list[0].finished': true,`list[${index}].data`: [],[`list[${index}].data`]: []
})

getCurrentPages 頁面棧使用

const pages = getCurrentPages();
const prePage = pages[pages.length - 2];// 獲取上一頁數據
console.log("prePage", prePage?.data.detail);
// 調用上一頁方法
prePage?.save();
// 修改上一頁數據
prePage.setData({"detail.name": "xr",
});

request 請求封裝

封裝 request
utils/http.js

import getBaseUrl from "./config";
import log from "./log";class CustomRequestInstance {static instance = null;static getInstance() {if (!this.instance) {this.instance = new CustomRequestInstance();}return this.instance;}request({ url = "", method = "get", data = {}, headers = {} }) {return new Promise((resolve, reject) => {wx.request({url: getBaseUrl() + url,header: {"content-type": "application/json",Authorization: `Bearer ${wx.getStorageSync("token")}`,...headers,},method: method.toUpperCase(),data: {...data,},success: function (res) {},fail: function (err) {log.error(`request-${url}-${err}`);reject(err);},});});}
}export default CustomRequestInstance;

封裝 api
services/common.js

import Services from "../utils/http";const http = Services.getInstance();class CommonServices {// 獲取城市async getCity() {const res = await http.request({ url: "/city" });return res;}
}export default new CommonServices();

使用

import CommonServices from "../../../services/common";const res = await CommonServices.getCity();

upload 封裝

import getUrl from "./config";/*** uploadFile 封裝* @param {*} Object { name = "file", filePath, ...rest }** @see [https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseMedia.html](https://developers.weixin.qq.com/miniprogram/dev/api/media/video/wx.chooseMedia.html)*/
export function customUpload({ name = "file", filePath, ...rest }) {return new Promise((resolve, reject) => {wx.uploadFile({url: `${getUrl()}/upload/image`,filePath,name,header: {Authorization: `Bearer ${wx.getStorageSync("token")}`,},...rest,success(res) {resolve(JSON.parse(res.data));},fail(error) {reject(error);},});});
}

組件

components/test/test.json

{"component": true,"usingComponents": {"van-icon": "@vant/weapp/icon/index"}
}

components/test/test.wxml

<view wx:if="{{show}}" class="mask"><van-icon class="remove" name="cross" catchtap="handleClose" />
</view>

components/test/test.js

Component({options: {// 在組件定義時的選項中啟用多slot支持multipleSlots: true,// 使用全局 app.wxssaddGlobalClass: true,},/*** 組件的屬性列表*/properties: {show: {type: Boolean,value: false,},},/*** 組件的初始數據*/data: {},// 監聽observers: {show: function (newVal) {console.log("newVal", newVal);},},// // 生命周期函數,可以為函數,或一個在methods段中定義的方法名lifetimes: {// 可以使用 setDataattached: function () {console.log("attached");},moved: function () {console.log("moved");},detached: function () {console.log("detached");},},//  // 組件所在頁面的生命周期函數pageLifetimes: {// 頁面進入show: function () {console.log("show");},// 頁面離開hide: function () {console.log("hide");},resize: function () {console.log("resize");},},/*** 組件的方法列表*/methods: {handleClose() {this.triggerEvent("close", { flag: false });},},
});
  • 實現默認插槽
Component({properties: {useDefaultSlot: {type: Boolean,value: false,},},
});

components/test/test.js

<view><view wx:if="{{ !useDefaultSlot }}">默認值</view><slot wx:else></slot><slot name="after"></slot>
</view>
{"usingComponents": {"x-text": "/components/test/test"}
}
<x-text useDefaultSlot><view>默認插槽</view><view slot="after">after 插槽</view>
</x-text>
  • 向外提供樣式類
<view class="custom-class"></view>
Component({externalClasses: ["custom-class"],
});
<x-text custom-class="text-14px"></x-text>
  • 獲取組件實例

可在父組件里調用 this.selectComponent ,獲取子組件的實例對象。
父組件

Page({getChildComponent: function () {const child = this.selectComponent(".my-component");},
});

wxs 使用

在當前 wxml 中

<view wx:if="{{util.isHas(idList, userId)}}"></view><wxs module="util">
function isHas(arr, val) {return arr.indexOf(val) >= 0
}
module.exports.isHas = isHas
</wxs>

單獨封裝方法
utils/utils.wxs

module.exports = {formatNums: function (val) {if (val >= 1000) {val = (val / 1000) + 'K'}return val},
}<wxs module="tools" src="/utils/utils.wxs"></wxs>{{tools.formatNums(item.type)}}

獲取元素信息 wx.createSelectorQuery()

如果在組件中,使用 this.createSelectorQuery()

const query = wx.createSelectorQuery();
query.select(".content").boundingClientRect();
query.exec((res) => {});

獲取列表數據/加載更多/下拉刷新

data: {list: [{page: 1,limit: 10,data: [],finished: false,},],
},onReachBottom() {this.getData();
},
async onPullDownRefresh() {await this.getData(true);wx.stopPullDownRefresh();
},
async getData(refresh = false) {try {const index = 0;let { page, limit, data, finished } = this.data.list[index];if (refresh) {page = 1;finished = false;}if (finished) return;const res = await SkillServices.getFairList(page, limit);let list = [];if (res?.data?.length < limit) finished = true;else finished = false;if (refresh) list = res?.data;else list = [...data, ...res.data];this.setData({[`list[${index}].data`]: list,[`list[${index}].page`]: page + 1,[`list[${index}].finished`]: finished,});} catch (error) {console.log(error);}
},

實現文本隱藏展示查看更多功能

text-ellipsis.wxml

<view class="relative" wx:if="{{desc}}"><text class="{{showMore?'x-ellipsis--l3':''}} " style="line-height: {{lineHight}}px" ><text catchtap="handleLink">{{desc}}</text><text class="absolute primary more" bindtap="handleReadMore" wx:if="{{showMore}}">查看全部</text><text class="absolute primary more" bindtap="handleHideMore" wx:if="{{isExceed && !showMore}}">收起</text></text>
</view>
<block wx:else><slot></slot>
</block>

text-ellipsis.js

// pages/mine/visit/components/text-ellipsis/text-ellipsis.js
Component({options: {addGlobalClass: true,},properties: {lineHight: {type: Number,value: 22,},desc: {type: null,value: "",},},data: {showMore: false,isExceed: false, // 是否超過三行},observers: {desc(newValue) {// 如果當前被截斷則直接返回if (this.data.showMore) return;if (newValue) this.init();},},methods: {handleLink() {this.triggerEvent("link");},handleHideMore() {this.setData({ showMore: true });},handleReadMore() {this.setData({ showMore: false });},init() {const { lineHight } = this.data;let showMore = false;let isExceed = false;var query = this.createSelectorQuery();query.select(".content").boundingClientRect();query.exec((res) => {var height = res[0]?.height;if (!height) return;var line = height / lineHight;if (line > 3) {showMore = true;isExceed = true;} else {showMore = false;isExceed = false;}this.setData({ showMore, isExceed });});},},
});
.more {bottom: 0;right: 0;background: #fff;padding-left: 10rpx;
}
.relative {position: relative;
}
.absolute {position: absolute;
}
.primary {color: var(--primary);
}

引入組件

{"usingComponents": {"x-text-ellipsis": "/components/text-ellipsis/text-ellipsis"}
}
<x-text-ellipsis desc="{{userInfo.desc}}"><view class="text-sm text-aaa">暫未填寫簡介</view>
</x-text-ellipsis>

訂閱消息封裝

export const requestSubscribeMessage = (tmplIds = ["MLCQvuq6kWY-jbH8Cxn-veoPZ6gJ8QTWiBpMV96mjs0"]) => {wx.requestSubscribeMessage({tmplIds,success(res) {console.log("requestSubscribeMessage res", res);// MLCQvuq6kWY-jbH8Cxn-veoPZ6gJ8QTWiBpMV96mjs0: "reject" 取消// MLCQvuq6kWY-jbH8Cxn-veoPZ6gJ8QTWiBpMV96mjs0: "accept" 同意tmplIds.forEach((tmplId) => {if (res[tmplId] === "accept") console.log(tmplId, "同意了");else if (res[tmplId] === "reject") console.log(tmplId, "拒絕了");});},fail(err) {console.log("requestSubscribeMessage err", err);},});
};

分享

onShareAppMessage(){return {title: '**',path: '/pages**',imageUrl: '/static/share.png'}
}

分包

others/pages/mine/mine.wxml
app.json

    ..."subPackages": [{"root": "others","pages": ["pages/mine/mine"]}],

防抖、節流

css

動畫

/* pages/idea/form/form.wxss */@keyframes opacity-show {0% {opacity: 0;}to {opacity: 1;}
}
@keyframes opacity-hide {0% {opacity: 1;}to {opacity: 0;}
}@keyframes scale-show {0% {transform: scale(0);}to {transform: scale(1);}
}
@keyframes scale-hide {0% {transform: scale(1);}to {transform: scale(0);}
}
<view style="animation: opacity-show 2s ease,scale-show 2s ease;"></view>
.x-ellipsis {overflow: hidden;white-space: nowrap;text-overflow: ellipsis;
}
.x-ellipsis--l2,
.x-ellipsis--l3 {-webkit-box-orient: vertical;display: -webkit-box;overflow: hidden;text-overflow: ellipsis;
}
.x-ellipsis--l2 {-webkit-line-clamp: 2;
}
.x-ellipsis--l3 {-webkit-line-clamp: 3;
}.arrow::after {content: "";width: 15rpx;height: 15rpx;border-top: 3rpx solid ##ccc;border-right: 3rpx solid ##ccc;transform: rotate(45deg);
}/* 數字、字母過長不換行 */
.break-all {word-break: break-all;
}scroll-view::-webkit-scrollbar {width: 0;height: 0;color: transparent;
}

修改 vant css 變量

page {--van-picker-confirm-action-color: #08bebe;
}

修改 input placeholder 樣式

<input value="{{ keyword }}" placeholder-class="placeholder-class" placeholder="請輸入" bindinput="handleInput" />
.placeholder-class {color: #bbbbbb;
}

textarea 設置行高后,光標與 placeholder 不對齊
解決方案:使用 text 替換 placeholder

iPhone 13 pro 遇到的問題:
text 不要放在 textarea 標簽內
定位后,給 text 一個事件,自動獲取焦點

<view class="relative"><textareaclass="absolute left-0 top-0"focus="{{focus}}"bindblur="onBlur"model:value="{{value}}"disable-default-paddingmaxlength="{{-1}}"/><text class="text-aaa text-14px leading-28px absolute left-0 top-0" bindtap="onFocus" wx:if="{{!value}}">提示:請輸入內容請輸入內容請輸入內容請輸入內容請輸入內容</text>
</view>
Page({data: {focus: false,value: "",},onFocus() {this.setData({ focus: true });},onBlur() {this.setData({ focus: false });},
});

Ios 底部安全距離

page {--ios-safe-bottom-low: constant(safe-area-inset-bottom); /* 兼容 iOS<11.2 */--ios-safe-bottom-higt: env(safe-area-inset-bottom); /* 兼容iOS>= 11.2 */
}
.safe-area-inset-bottom {padding-bottom: var(--ios-safe-bottom-low);padding-bottom: var(--ios-safe-bottom-higt);
}
setFormValue(value, num = undefined) {value = value.trim();if (num) value = value.slice(0, num);else value = value.slice(0);return value;
},

echarts-for-weixin

動態設置數據如下

echarts-for-weixin

xx.json

{"usingComponents": {"ec-canvas": "../../ec-canvas/ec-canvas"}
}

xx.wxml

<view class="container"><ec-canvas id="mychart-dom-bar" canvas-id="mychart-bar" ec="{{ ec }}"></ec-canvas></view>

xx.wxss

ec-canvas {width: 100%;height: 100%;}

xx.js

import * as echarts from '../../ec-canvas/echarts';let chart = null;
let option;
function initChart(canvas, width, height, dpr) {chart = echarts.init(canvas, null, {width: width,height: height,devicePixelRatio: dpr // 像素});canvas.setChart(chart);option = {xAxis: {type: "category",data: ["今日已完成", "本周已完成", "本月已完成", "本季度已完成"],},yAxis: {type: "value",},series: [{data: [10, 20, 150, 8],type: "bar",},],};chart.setOption(option);return chart;
}Page({data: {ec: {onInit: initChart}},onLoad() {setTimeout(() => {option.series[0].data = [10, 20, 150, 8, 70]chart.setOption(option);}, 2000);},
});

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/38836.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/38836.shtml
英文地址,請注明出處:http://en.pswp.cn/news/38836.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

域名配置HTTPS

一、注冊域名 這個可以在各大平臺注冊&#xff0c;具體看一下就會注冊了&#xff0c;自己挑選一個自己喜歡的域名。 步驟一般也就是先實名&#xff0c;實名成功了才能注冊域名。 二、辦理SSL證書 這里使用的是阿里云的SSL免費證書 1、申請證書 二、填寫申請 三、域名綁定生…

公司電腦三維圖紙加密、機械圖擋加密軟件

機械圖紙加密軟件的問世&#xff0c;讓很多的網絡公司都大受其帶來的工作中的便利。在安裝了機械圖紙加密軟件后&#xff0c;不僅可以很好的管理員工在工作時的上網娛樂&#xff0c;在對整個公司員工的工作效率上也有著明顯的提高&#xff0c;那么對于機械圖紙加密軟件的具體特…

【C#】靜默安裝、SQL SERVER靜默安裝等

可以通過cmd命令行來執行&#xff0c;也可以通過代碼來執行&#xff0c;一般都需要管理員權限運行 代碼 /// <summary>/// 靜默安裝/// </summary>/// <param name"fileName">安裝文件路徑</param>/// <param name"arguments"…

word 應用 打不開 顯示一直是正在啟動中

word打開來顯示一直正在啟動中&#xff0c;其他調用word的應用也打不開&#xff0c;網上查了下以后進程關閉spoolsv.exe,就可以正常打開word了

演進式架構

演進能力是一種元特征和保護其他所有架構特征的架構封裝器IEEE 的軟件架構定義中的41 視圖模型。它關注不同角色的不同視角&#xff0c;將整個系統劃分成了邏輯視圖、開發視圖、進程視圖和物理視圖架構師確定了可審計性、數據、安全性、性能、合法性和伸縮性是該應用的關鍵架構…

機器學習:特征工程之特征預處理

目錄 特征預處理 1、簡述 2、內容 3、歸一化 3.1、魯棒性 3.2、存在的問題 4、標準化 ?所屬專欄&#xff1a;人工智能 文中提到的代碼如有需要可以私信我發給你&#x1f60a; 特征預處理 1、簡述 什么是特征預處理&#xff1a;scikit-learn的解釋&#xff1a; provide…

linux系統服務學習(六)FTP服務學習

文章目錄 FTP、NFS、SAMBA系統服務一、FTP服務概述1、FTP服務介紹2、FTP服務的客戶端工具3、FTP的兩種運行模式&#xff08;了解&#xff09;☆ 主動模式☆ 被動模式 4、搭建FTP服務&#xff08;重要&#xff09;5、FTP的配置文件詳解&#xff08;重要&#xff09; 二、FTP任務…

Python基礎語法入門(第二十天)——文件操作

一、基礎內容 在Python中&#xff0c;路徑可以以不同的表現形式進行表示。以下是一些常用的路徑表現形式&#xff1a; 1. 絕對路徑&#xff1a;它是完整的路徑&#xff0c;從根目錄開始直到要操作的文件或文件夾。在Windows系統中&#xff0c;絕對路徑以盤符開始&#xff0c;…

【學會動態規劃】環形子數組的最大和(20)

目錄 動態規劃怎么學&#xff1f; 1. 題目解析 2. 算法原理 1. 狀態表示 2. 狀態轉移方程 3. 初始化 4. 填表順序 5. 返回值 3. 代碼編寫 寫在最后&#xff1a; 動態規劃怎么學&#xff1f; 學習一個算法沒有捷徑&#xff0c;更何況是學習動態規劃&#xff0c; 跟我…

CSS 兩欄布局和三欄布局的實現

文章目錄 一、兩欄布局的實現1. floatmargin2. flaotBFC3. 定位margin4. flex 布局5. grid布局 二、三欄布局的實現1. float margin2. float BFC3. 定位 margin(或者定位BFC)4. flex布局5. 圣杯布局6. 雙飛翼布局 一、兩欄布局的實現 兩欄布局其實就是左側定寬&#xff0c;…

高層建筑全景vr火災隱患排查模擬培訓軟件助力群眾防范火災傷害

隨著城市化進程的加快&#xff0c;樓宇建筑的數量也在不斷增加。然而&#xff0c;樓宇消防安全問題也日益突出。為了提高樓宇員工和居民的消防安全意識&#xff0c;樓宇VR消防安全教育培訓應運而生。VR安全培訓公司深圳華銳視點制作的樓宇vr消防安全教育培訓&#xff0c;包括消…

谷粒商城第十一天-完善商品分組(主要添上關聯屬性)

目錄 一、總述 二、前端部分 2.1 改良前端獲取分組列表接口及其調用 2.2 添加關聯的一整套邏輯 三、后端部分 四、總結 一、總述 前端部分和之前的商品品牌添加分類差不多。 也是修改一下前端的分頁獲取列表的接口&#xff0c;還有就是加上關聯的那一套邏輯&#xff0c;…

nginx負載均衡與反向代理與正向代理

負載均衡&#xff1a;通過反向代理來實現 正向代理的配置方法。 正向代理&#xff1a; 工作原理&#xff1a;用戶端直接訪問不了&#xff0c;需要通過代理服務器來訪問web服務器&#xff0c;用戶端先訪問代理服務器&#xff0c;再訪問web服務器。web服務器響應給代理服務器&a…

【C語言】調試技巧

目錄 一、什么是bug? 二、調試 1.一般調試的步驟 2.Debug 和 Release 三、調試環境準備 四、調試時要查看的信息 1.查看臨時變量的值 2.查看內存信息 3.查看調用堆棧 4.查看反匯編信息 5.查看寄存器 五、練習 六、常見的coding技巧 七、const的作用 八、編程常見…

Linux - MongoDB 數據庫自動退出服務問題/閃退

問題&#xff1a;MongoDB 自動退出服務問題 原因&#xff1a; 由于 Mongodb 服務&#xff0c;使用過多系統內存&#xff0c;導致系統強制停止 Mongodb 服務。 解決方法&#xff1a; 在 mongodb.conf 配置文件內&#xff0c;添加新配置內容&#xff1a; wiredTigerCacheSi…

POI與EasyExcel--寫Excel

簡單寫入 03和07版的簡單寫入注意事項&#xff1a; 1. 對象不同&#xff1a;03對應HSSFWorkbook&#xff0c;07對應XSSFWorkbook 2. 文件后綴不同&#xff1a;03對應xls&#xff0c;07對應xlsx package com.zrf;import org.apache.poi.hssf.usermodel.HSSFWorkbook; import …

如何應用項目管理軟件進行敏捷開發管理

敏捷開發&#xff08;Agile Development&#xff09;是一種軟件開發方法論&#xff0c;強調在不斷變化的需求和環境下&#xff0c;通過迭代、協作和自適應的方式來開發軟件。敏捷方法的目標是提供更快、更靈活、更高質量的軟件交付&#xff0c;以滿足客戶需求并實現項目成功。 …

服務器數據恢復-EqualLogic存儲RAID5數據恢復案例

服務器數據恢復環境&#xff1a; 一臺DELL EqualLogic存儲中有一組由16塊SAS硬盤組建的RAID5陣列。存儲存放虛擬機文件&#xff0c;采用VMFS文件系統&#xff0c;劃分了4個lun。 服務器故障&檢測&分析&#xff1a; 存儲設備上有兩個硬盤指示燈顯示黃色&#xff0c;存儲…

【Windows 常用工具系列 6 -- CSDN字體格式(字體、顏色、大小)、背景色設置】

文章目錄 背景字體大小設置字體顏色設置字體類型背景色 上篇文章&#xff1a;Windows 常用工具系列 5 – Selenium IDE的使用方法 下篇文章&#xff1a;Windows 常用工具系列 7 – 禁用win10自帶的微軟輸入法 背景 Markdown是一種輕量級標記語言&#xff0c;它的目標是實現“…

1022.從根到葉的二進制之和

目錄 一、題目 二、代碼 一、題目 二、代碼 /*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nu…