1.vscode 插件
uni-create-view 快速nui-app页面的
uni-helper uni-app代码提示的
uniapp小程序扩展 鼠标悬停查文档
TypeScript Vue Plugin (Volar)
Vue Language Features (Volar)
Eslint
Prettier 禁用
Error Lens 行内提示报错
Turbo Console Log 打log插件
Code Spell Checker 检查拼写插件
"types": ["@dcloudio/types", "miniprogram-api-typings", "@uni-helper/uni-app-types","@uni-helper/uni-ui-types"]
miniprogram-api-typings 是一种增强小程序开发体验的工具,特别适用于使用 TypeScript 进行小程序开发的开发者。
@uni-helper/uni-app-types 是一个用于增强 uni-app 开发体验的 TypeScript 类型声明库,它可以帮助你在编写跨平台应用时获得更准确的代码提示和类型检查,提高代码质量和开发效率。
@uni-helper/uni-ui-types 是一个为 uni-ui 组件库提供的 TypeScript 类型声明库。
1.1 uni-create-view 插件设置
1.2 VsCode对于json格式文件允许添加注释设置
files.associations
1.3 TS托管配置
官网解释:
https://cn.vuejs.org/guide/typescript/overview.html#takeover-mode
2.统一代码风格
- 安装
eslint
+prettier
pnpm i -D eslint prettier eslint-plugin-vue @vue/eslint-config-prettier @vue/eslint-config-typescript @rushstack/eslint-patch @vue/tsconfig
新建 .eslintrc.cjs
文件,添加以下 eslint
配置
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution') // 加载模块解析的修复补丁。
// 导出一个对象,该对象包含ESLint的配置信息。
module.exports = {
root: true, // 指定该配置文件为根配置文件。
extends: [ // 指定扩展的规则集,这里包括了一些规则的插件和扩展。
'plugin:vue/vue3-essential', // Vue.js 3.x项目的基本规则。
'eslint:recommended', // ESLint官方推荐的规则。
'@vue/eslint-config-typescript', // Vue.js项目中使用TypeScript的规则。
'@vue/eslint-config-prettier',// 与Prettier代码格式化工具一起使用的规则。
],
// 小程序全局变量
globals: { //指定全局变量,这些变量可以在代码中直接使用而不需要声明。
uni: true,
wx: true,
WechatMiniprogram: true,
getCurrentPages: true,
getApp: true,
UniApp: true,
UniHelper: true,
App: true,
Page: true,
Component: true,
AnyObject: true,
},
parserOptions: { //指定解析器选项,这里将ECMAScript版本设置为最新。
ecmaVersion: 'latest',
},
rules: { //指定自定义的规则,这里列出了一些自定义规则的配置。
'prettier/prettier': [ //使用Prettier的规则进行代码格式化,包括使用单引号、省略分号、限制一行的最大字符数、使用逗号结尾等。
'warn',// 表示如果代码与这些配置不符合,ESLint将发出警告。具体的配置包括:
{
singleQuote: true, // 使用单引号而不是双引号。
semi: false, //不使用分号结尾。
printWidth: 100, // 限制一行的字符数为100。
trailingComma: 'all', // 使用逗号结尾的方式。
endOfLine: 'auto', // 自动识别换行符。
},
],
'vue/multi-word-component-names': ['off'], // 禁用在Vue组件名中使用多个单词的规则。
'vue/no-setup-props-destructure': ['off'], // 禁用在Vue组件props中使用解构赋值的规则。
'vue/no-deprecated-html-element-is': ['off'], // 禁用使用已废弃的`is`属性的规则。
'@typescript-eslint/no-unused-vars': ['off'], // 禁用未使用的TypeScript变量的规则。
},
}
package.json 中添加
{
"script": {
// ... 省略 ...
"lint": "eslint . --ext .vue,.js,.ts --fix --ignore-path .gitignore"
}
}
然后 运行 pnpm lint 自动修复了
- https://prettier.io/docs/en/options.html 常见规则
vscode 开启 eslint 自动修复
json
"editor.codeActionsOnSave": {
"source.fixAll": true,
},
3.使用uCharts
组件方式
快速上手
npm i @qiun/ucharts
3.1 或者使用uniapp对应插件图表
https://limeui.qcoon.cn/#/echart
https://ext.dcloud.net.cn/plugin?id=4899
4.报错相关
Some selectors are not allowed in component wxss, including tag name selectors, ID selectors, and attribute selectors.
不能用标签选择器 如 button text 这样的 应该加类名
5.获取屏幕边界到安全区域的距离
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
6.分享
onShareAppMessage
// 分享的信息
onShareAppMessage((res) => {
// 分享事件来源:menu(右上角分享按钮)
return {
title: '请来填写一下个人信息!',
path: '/pages/addInfo/index',
}
})
7.内置组件picker的踩坑
<view class="uni-title uni-common-pl">地区选择器</view>
<view class="uni-list">
<view class="uni-list-cell">
<view class="uni-list-cell-left"> 当前地区为: </view>
<view class="uni-list-cell-db">
<picker
mode="region"
:value="regionList"
@change="onRegionChange"
@cancel="onRangeCancel"
level="city"
>
<view class="" v-if="regionList.length">{{ regionList[0] }} - {{ regionList[1] }}</view>
<view v-else>{{ '请选择城市' }}</view>
</picker>
</view>
</view>
</view>
源码里面是有 选择器层级的 province 省级 city 市级 region 区级 sub-district 街道级
但是官网文档没有显示 然后微信开发者工具也不好使,一度以为废弃了,偶然间发现*****mmp的手机预览就可以
8.安全区域问题预览与真机调试
const { safeAreaInsets } = uni.getSystemInfoSync()
console.log(safeAreaInsets, 'safeAreaInsets')
:style="{ bottom: safeAreaInsets?.bottom + 'px' }"
但是如果是 空标签 加上<view :style="{ height: safeAreaInsets?.bottom + 'px' }" style="width: 100%" />
就可以 我也没搞清楚两个组件写法是一样的 只不过一个是一上来就加载 一个通过boolean 去显示之后就可以使用了 我怀疑是声明周期的问题
但是如果给获取这段代码 放在生命周期里面 页面加载就会闪,我看网上一般都是直接放在setup语法糖里面就很奇怪
后来不好使的这个页面 我就用css变量替换了
bottom: 0;
bottom: constant(safe-area-inset-bottom); // 修复 真机调试情况下 css动态设置失效问题 采用变量控制
bottom: env(safe-area-inset-bottom);
or 上面的 苹果手机弹性 会看到透明区域
bottom: 0;
// bottom: constant(safe-area-inset-bottom); // 修复 真机调试情况下 css动态设置失效问题 采用变量控制
// bottom: env(safe-area-inset-bottom);
left: 0;
height: calc(110rpx + env(safe-area-inset-bottom));
background-color: #fff;
在预览模式下 可以使用 在真机模式下 safeAreaInsets
为undefined
具体为什么我也不知道!!!
文档:https://ask.dcloud.net.cn/article/35564
9.键盘弹出高度
// 监听键盘高度变化
uni.onKeyboardHeightChange((obj) => {
// 获取系统信息
let _sysInfo = uni.getSystemInfoSync()
let _heightDiff = _sysInfo.screenHeight - _sysInfo.windowHeight
let _diff = obj.height - _heightDiff
// 键盘高度
let height = (_diff > 0 ? _diff : 0) - 2 + 'px'
console.log(height, 'heightheight')
})
10.样式覆盖
::v-deep
uni-data-select {
flex: 1;
::v-deep.uni-select {
border: none;
padding: 0;
}
}
11.全局组件自动导入问题
(1).src\components\hbcy-icon-title.vue
(2).src\types\components.d.ts
// src/types/components.d.ts 全局组件类型声明
import HbcyIconTitle from '@/components/hbcy-icon-title.vue'
declare module '@vue/runtime-core' {
export interface GlobalComponents {
HbcyIconTitle: typeof HbcyIconTitle
}
}
(3).src\pages.json
与 "pages"同级
// 组件自动导入
"easycom": {
// 是否开启自动扫描 @/components/$1/$1.vue 组件
"autoscan": true,
"custom": {
// uni-ui 规则如下配置
"^uni-(.*)": "@dcloudio/uni-ui/lib/uni-$1/uni-$1.vue",
// 以 hbcy- 开头的组件,在 components 目录中查找
"^hbcy-(.*)": "@/components/hbcy-$1.vue"
}
}
(4).使用
<hbcy-icon-title />
12.input 样式自定义
placeholder
的样式自定义可以用placeholder-style
or placeholder-class
<input
class="item-input"
placeholder="请输入缴费基数"
placeholder-style="font-size:28rpx"
type="digit"
focus
/>
::v-deep.input-placeholder {
font-size: 28rpx;
}
https://uniapp.dcloud.net.cn/component/input.html#属性说明
13.表单回显小知识
需求
: A页面填完信息跳转到B页面,当B页面返回的时候,A页面需要保留刚刚没跳转B之前的信息
正常来说利用本地存储,跳转之前存一下,跳转之后回显
但是小程序orUniapp有一个回调上一页功能uni.navigateBack()
如果使用它,那么没有变化的数据就不需要去再次存储以及回显
(左上角返回 和 uni.navigateBack() 是一样的功能)
因为返回的这个操作类似于浏览器回退(不刷新数据) 需要刷新的时候可以写 onShow!
const onClickSend = () => {
// TODO
uni.navigateBack()
// uni.navigateTo({
// url: '/pages/addInfo/index',
// })
setTimeout(() => {
uni.showToast({
title: '保存成功',
icon: 'none',
mask: true,
})
}, 500)
}
扩展
setTimeout(() => uni.navigateBack({
delta: 1
// success() {
// let pages = getCurrentPages() // 获取当前挂载的路由数组
// let prePage = pages[pages.length - 2] as any // 获取 上一个页面
// if (prePage.route === 'enterpriseZone/enterpriseZoneSubmitOrder/enterpriseZoneSubmitOrder') {
// prePage.orderDetails() // 当返回成功的时候调用上一级页面的回调
// }
// }
}), 1000)
13.元素节点操作-uni.createSelectorQuery()
注意:想要拿到元素实例,需要在实例已经挂载到页面上才可以
//1、首先导入当前组件的实例
import {getCurrentInstance} from "vue";
var currentInstance = getCurrentInstance();
//2、添加上in方法
const inputQuery = uni.createSelectorQuery().in(currentInstance)
// 获取输入框
inputQuery.select('#input').boundingClientRect((rect) => {
console.log("得到节点信息" , rect);
})
.exec()
示例图:
14. uni.createInnerAudioContext()音频组件控制API
官方地址:https://uniapp.dcloud.net.cn/api/media/audio-context.html#
14.1 踩坑1 获取音频时长NAN/undefined/0的问题
增加定时器||延时器才能获取到
innerAudioContext.onCanplay(() => {
let intervalId = setInterval(() => {
if (innerAudioContext.duration !== 0) {
clearInterval(intervalId)
isDurationInitialized = true
console.log('音频时长', innerAudioContext.duration)
audioDuration.value = Math.round(innerAudioContext.duration)
}
}, 500)
})
14.2 踩坑2 Ios端获取两次音频时长问题
增加判断
let isDurationInitialized = false
innerAudioContext.onCanplay(() => {
let intervalId = setInterval(() => {
if (innerAudioContext.duration !== 0) {
clearInterval(intervalId)
if (!isDurationInitialized) {
isDurationInitialized = true
console.log('音频时长', innerAudioContext.duration)
audioDuration.value = Math.round(innerAudioContext.duration)
}
}
}, 500)
})
15. 微信第三方插件 OCR支持
https://mp.weixin.qq.com/wxopen/pluginbasicprofile?action=intro&appid=wx4418e3e031e551be&token=&lang=zh_CN
其实就是在manifest.json
配置
/* 小程序特有相关 */
"mp-weixin": {
"appid": "xxxxxx",
"setting": {
"urlCheck": false
},
"plugins": {
"WechatSI": {
"version": "0.3.5",
"provider": "wx069ba97219f66d99"
},
+ "ocr-plugin": {
+ "version": "3.1.3",
+ "provider": "wx4418e3e031e551be"
+ }
},
"usingComponents": true
},
在pages.json
中
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8",
+ "usingComponents": {
+ "ocr-navigator": "plugin://ocr-plugin/ocr-navigator"
+ }
},
进行配置,官网说的比较模棱两可
使用
身份证类型示例
<script setup lang="ts">
// 扫描
const onScanning = (e: any) => {
const {
id: { text: idCard },
name: { text: name },
} = e.detail
// TODO
console.log(e, 'onScanning')
console.log(idCard, name)
}
</script>
<template>
<ocr-navigator @onSuccess="onScanning" :opposite="false">
<view class="title-r">
<text>证件扫描</text>
<view class="title-img">
<image src="@/static/images/ewm.png" mode="aspectFill" />
</view>
</view>
</ocr-navigator>
</template>
16.小程序内识别二维码跳转
uni.scanCode({
success: function (res) {
console.log(res, 'res')
console.log('条码类型:' + res.scanType)
console.log('条码内容:' + res.result)
},
})
扫码识别只能扫自己小程序的码,第三方以及他人的码只能拿到如下这种,并不能直接跳转第二种方式长按识别二维码跳转
只能识别小程序码参考链接:
https://developers.weixin.qq.com/community/develop/article/doc/00008e4f3bc538998bfb344ec56413
17.自定义底部弹窗及文字
uni.showActionSheet(options):https://uniapp.dcloud.net.cn/uni-app-x/api/prompt.html#showactionsheet
uni.showActionSheet({
title: '标题',
itemList: ['预览文件', '转发邮箱'],
success: (e) => {
console.log(e.tapIndex)
uni.showToast({
title: '点击了第' + e.tapIndex + '个选项',
icon: 'none',
})
},
fail: (e) => {
console.log(e)
},
})
18.预览文件xlsx等
uni.openDocument(OBJECT):https://uniapp.dcloud.net.cn/api/file/file.html#opendocument注意
:需要在小程序后台-开发-开发管理-开发设置-服务器域名-downloadFile合法域名配置域名
uni.downloadFile({
url: 'https://example.com/somefile.pdf', // 文件路径 一般为OSS的
success: function (res) {
var filePath = res.tempFilePath;
uni.openDocument({
filePath: filePath,
showMenu: true,
success: function (res) {
console.log('打开文档成功');
}
});
}
});
19.button的默认样式
个人头像的业务时发现有4个黑点其实就是 after样式
// 用户头像
const avatarUrl = ref('')
const onChooseavatar: UniHelper.ButtonOnChooseavatar = (e) => {
avatarUrl.value = e.detail.avatarUrl
}
<button class="AvatarView" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
<view>
<open-data v-if="!avatarUrl" type="userAvatarUrl"></open-data>
<image class="Avatarimgae" v-else :src="avatarUrl" mode="scaleToFill" />
</view>
</button>
<style lang="scss" scoped>
.AvatarView {
width: 200rpx;
height: 200rpx;
border-radius: 50%;
padding: 0;
}
.Avatarimgae {
width: 200rpx;
height: 200rpx;
}
</style>
在全局加上样式
button::after {
border: none;
}
问题:
解决:
20.动态组件的使用
目前不支持
https://ask.dcloud.net.cn/question/138772?item_id=255123&rf=false
在网上有看到vue3+uniapp使用动态组件的 但是我测试还是不行!
jb51.net/javascript/300333nib.htm#_label2
21.重新加载当前页面组件生命周期
场景:当前页面有多个tab,但是tab下有一个共用的组件,和不同列表,vue3+ts的写法的时候,公用的组件只有初始的时候拿到了props的传参因为我在组件里面调用全局方法二次加工了,所以想到了重新加载组件生命周期
const enterpriseSelectMonth = ref(false)
// 切换组件重新加载生命周期
const onToggle = () => {
enterpriseSelectMonth.value = false
nextTick(() => {
enterpriseSelectMonth.value = true
})
}
<!-- 日期选择区域 -->
<enterprise-select-month
v-if="enterpriseSelectMonth"
:data="selectMonth"
@confirm-popup="onChangePopup"
/>
22.文字中间空格一个文字的距离 实现左右两端对齐
一开始想到了中间文字透明,感觉low;然后又想到了用flex布局,但是也low
最后通过css的伪元素实现::first-letter
UI效果图:
<view class="bottom-item">
<text class="lable">个<text style="opacity: 0">人</text>税:</text>
<text class="value">1,234,567.89</text>
</view>
<!-- 需要lable 去掉 display: inline-block; -->
<view class="bottom-item flex_row_flex-start_center">
<view class="lable flex_row_space-between_center"><text>个</text><text>税:</text></view>
<text class="value">1,234,567.89</text>
</view>
<-- 最完美 -->
<view class="bottom-item">
<text class="lable1">个税:</text>
<text class="value">1,234,567.89</text>
</view>
.lable {
width: 112rpx;
display: inline-block;
}
.lable1 {
width: 112rpx;
display: inline-block;
&::first-letter {
margin-right: 1em; /* 负的字体大小 */
font-size: 28rpx; /* 可以调整首字母的大小 */
}
}
23.实现点击按钮复制功能 setClipboardData
uni.setClipboardData
设置系统剪贴板的内容。
https://uniapp.dcloud.net.cn/api/system/clipboard.html#setclipboarddata
<script setup lang="ts">
const copy = (val: string) => {
uni.setClipboardData({
data: val, // 这里是个坑接受字符串类型 value转化为字符串
success: function () {
//调用方法成功
console.log('success')
},
})
}
</script>
<image
class="image"
:src="`${IMAGE_BASEURl}copy_icon.png`"
mode="aspectFill"
@tap="copy('测试文案')"
/>
24.scss 动态减去屏幕上+下安全区域失效问题
24.1 获取获取窗口信息 uni.getWindowInfo()
uni.getWindowInfo()
https://uniapp.dcloud.net.cn/api/system/getWindowInfo.html#getwindowinfo
const { screenHeight, screenWidth, windowHeight, windowWidth } = uni.getWindowInfo()
console.log(screenHeight, '屏幕高度') //屏幕高度
console.log(screenWidth, '屏幕宽度') //屏幕宽度
console.log(windowHeight, '可操作页面高度') //可操作页面高度
console.log(windowWidth, '可操作页面宽度') //可操作页面宽度
console.log('获取窗口信息')
24.2 获取系统信息 uni.getSystemInfoSync & uni.getSystemInfo
1.同步获取 标题 5 演示过
https://uniapp.dcloud.net.cn/uni-app-x/api/get-system-info.html#getsysteminfosync
const { safeAreaInsets } = uni.getSystemInfoSync()
2.异步获取
https://uniapp.dcloud.net.cn/api/system/info.html#getsysteminfo
// 系统信息的概念
uni.getSystemInfo({
success: (res) => {
console.log(res)
console.log(res.screenHeight) //屏幕高度
console.log(res.screenWidth) //屏幕宽度
console.log(res.windowHeight) //可操作页面高度
console.log(res.windowWidth) //可操作页面宽度
},
})
uni.getSystemInfo({
success: (res) => {
console.log(res)
console.log(res.screenHeight) //屏幕高度
console.log(res.screenWidth) //屏幕宽度
console.log(res.windowHeight) //可操作页面高度
console.log(res.windowWidth) //可操作页面宽度
},
})
24.3 获取胶囊相关 getMenuButtonBoundingClientRect()
https://uniapp.dcloud.net.cn/api/ui/menuButton.html#getmenubuttonboundingclientrect
let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
console.log(menuButtonInfo.width) //宽度,单位:px
console.log(menuButtonInfo.height) //高度,单位:px
console.log(menuButtonInfo.top) //上边界坐标,单位:px
console.log(menuButtonInfo.right) //右边界坐标,单位:px
console.log(menuButtonInfo.bottom) //下边界坐标,单位:px
console.log(menuButtonInfo.left) //左边界坐标,单位:px
24.4 遇到的问题css动态计算失效以及扩展新知识 vue3.2中css引用v-bind使用变量
// 最终解决方案
.enterprise-scroll-view {
// height: calc(100% - 774rpx - env(safe-area-inset-top) - env(safe-area-inset-bottom)); // 失效
height: v-bind(dynamicHeight); // 扩展知识
width: 100%;
background-color: #dd2520;
}
不知道为什么 在scc里同时 - 头部 - 底部安全区域 就只能减一个 (因为自定义导航所以要-top-bottom)文章来源:https://www.toymoban.com/news/detail-673815.html
onMounted(() => {
// 计算元素的动态高度
const fixedValue = 774 // 固定值
dynamicHeight.value = `calc(100% - ${fixedValue}rpx - ${safeAreaInsets?.bottom!}px - ${safeAreaInsets?.top!}px)`
})
// 解决方案一
<scroll-view scroll-y class="enterprise-scroll-view" :style="{ height: dynamicHeight }">
<view v-for="i in 50" :key="i">{{ i }}</view>
</scroll-view>
// 解决方案二
<scroll-view
scroll-y
class="enterprise-scroll-view"
:style="{
height: `calc(100% - 774rpx - ${safeAreaInsets?.bottom!}px - ${safeAreaInsets?.top!}px)`,
}"
>
<view v-for="i in 50" :key="i">{{ i }}</view>
</scroll-view>
25.复制API uni.setClipboardData
const onClone = () => {
uni.setClipboardData({
data: code.value,
success: () => {
uni.showToast({
title: '复制成功',
})
},
})
}
26.H5跳转小程序相关
目前我了解到
外部浏览器 h5跳转微信小程序就两个办法:
1.进行小程序短链跳转,这个需要后台返回短链
链接如下两个:
(1):https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/url-scheme.html
(2):https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/url-link.html
2.需要云函数静态网页支持,咱们项目没用云函数
链接:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/staticstorage/jump-miniprogram.html微信内分为网页、微信公众号、小程序跳转
1.可以使用微信开放标签,链接:
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_Open_Tag.html 跳转小程序:wx-open-launch-weapp文章来源地址https://www.toymoban.com/news/detail-673815.html
到了这里,关于个人首次使用UniAPP使用注意事项以及踩坑的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!