小程序 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.mzph.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…