个人首次使用UniAPP使用注意事项以及踩坑

个人首次使用UniAPP使用注意事项以及踩坑

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 检查拼写插件

Todo Tree 项目TODO的地方做好记录

"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;

在预览模式下 可以使用 在真机模式下 safeAreaInsetsundefined

具体为什么我也不知道!!!

文档: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"
   or
   placeholder-class="input-placeholder"
   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)

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

27.获取图片宽高来动态定义图片 uni.getImageInfo()

21.1uni.getImageInfo()方法获取图片信息宽高,然后再赋值渲染

注意:小程序下获取网络图片信息需先配置download域名白名单才能生效。
https://uniapp.dcloud.net.cn/api/media/image.html#getimageinfo

  // 由于方法是异步的,渲染时高度会不生效,所以要加await
  let { width, height } = await uni.getImageInfo({ src: imageUrl })
  // 取到图片的宽高
  console.log('🚀 ~ onLoad ~ width, height:', width, height)

27.2 当宽度固定时使用image的属性 mode=“widthFix”

使用这个属性高度自适应也可以!!!
https://uniapp.dcloud.net.cn/component/image.html#image

27.3 解决图片底部留白问题

原以为只有web上会有这个问题,没想到小程序也有这个问题!
vertical-align: middle; or vertical-align: bottom; 就解决了

28.自定义uni-datetime-picker 组件样式 区间选择时样式

// 确认按钮
:deep(.uni-datetime-picker--btn) {
  background: var(--unnamed, #d80c18);
  color: #fff;
  font-family: PingFang SC;
  font-size: 14px;
  font-weight: 400;
}
// 选中区域
:deep(.uni-calendar-item--multiple) {
  background-color: #FFF3F4;
}
// 前置选项背景
:deep(.uni-calendar-item--before-checked) {
  background-color: pink!important;
}
// 后置选项背景
:deep(.uni-calendar-item--after-checked) {
  background-color: #d80c18!important;
}

29.AtoB B返回A 携带参数

从A页面uni.navigateTo 去B 进行然后从B uni.navigateBack 回到A 要拿到一些B页面的参数
可通过getCurrentInstance + getOpenerEventChannel 来实现

A页面

  uni.navigateTo({
    url: `/pagesInformationForm/informationUpload/index?${useEncodeGetParams(params)}`,
    events: {
      // 为指定事件添加一个监听器,获取被打开页面传送到当前页面的数据
      acceptDataFromOpenedPage: (data: any) => {
        console.log(data)
        // 当跳转后的页面触发此事件即可传递参数过来, 此时就可以修改页面其他所有相修改的数据了
        formInfo.value.uploadNum = data.data
      },
    },
    // success: (res) => {
    //   // 通过eventChannel向被打开页面传送数据
    //   res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'data from starter page' } as any)
    // },
  })

B页面

<script setup lang="ts">
import { getCurrentInstance } from 'vue'
// 获取实例ps:只能在外层使用
const instance = getCurrentInstance()

let eventChannel = instance?.proxy?.getOpenerEventChannel()
// 通过监听上个页面的uni.navigateTo的events中定义的事件传递参数
eventChannel.emit('acceptDataFromOpenedPage', { data: currentUploadNum.value })
</script>

全局.d.ts文件 临时写的

declare module 'vue' {
  export interface ComponentCustomProperties {
    getOpenerEventChannel: any
  }
}

30.movable-area 屏幕内滑动

      <movable-area class="movable-area" :style="top:calc(88rpx + ${statusBarHeight}px);height: calc(100vh - 88rpx - ${statusBarHeight}px)">
        <movable-view class="movable-view" :x="startX" :y="startY" direction="all" out-of-bounds>
          <button open-type="share" class="share-btn">
            <image :src="`${IMAGE_BASEURl}index_share_icon.png`" mode="aspectFill" />
          </button>
        </movable-view>
      </movable-area>
  .movable-area {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    z-index: 99;

    .movable-view {
      pointer-events: auto;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 86rpx;
      height: 90rpx;
      .share-btn {
        all: unset;
        width: 86rpx;
        height: 90rpx;
      }
    }
  }

31.获取标签在页面上的信息

<template>
  <view>
      <view id="targetId">我是要获取的标签</view>
  </view>
</template>
<script setup>
import { getCurrentInstance } from 'vue';

const instance = getCurrentInstance();

const query = uni.createSelectorQuery().in(instance);

query.select('#targetId').boundingClientRect(data => {
  if (data) {
    console.log("获取到布局信息", data);
    // 这里返回的data就是我们需要的dom结构
  }
}).exec();
</script>

chagpt给出的错误代码!!!

const query = uni.createSelectorQuery().in(this);
query.select('#target').boundingClientRect(data => {
  console.log(data)
}).exec();

32.在小程序中使用企业微信客服

效果
在这里插入图片描述

vue文件

  <cell
    bind:startmessage="startmessage"
    bind:completemessage="completemessage"
    plugid="xxxx"
  />
  <image
    :style="{ width: '200rpx', height: '200rpx' }"
    src="../../static/test/er.png"
    show-menu-by-longpress="true"
    mode="aspectFill"
  />
  <image
    :style="{ width: '200rpx', height: '200rpx' }"
    src="../../static/test/card.png"
    show-menu-by-longpress="true"
    mode="aspectFill"
  />

page.json

"globalStyle": {
	"navigationBarTextStyle": "black",
	"navigationBarTitleText": "uni-app",
	"navigationBarBackgroundColor": "#ffffff",
	"backgroundColor": "#F8F8F8",
	"usingComponents": {
		"cell": "plugin://contactPlugin/cell"
	}
}

manifest.json

"mp-weixin": {
    "appid": "appid",
    "setting": {
        "urlCheck": false
    },
    "plugins": {
        "contactPlugin": {
            "version": "1.4.3",
            "provider": "wx104a1a20c3f81ec2"
        }
    },
    "usingComponents": true,
    "optimization": {
        "subPackages": true
    }
}

企业微信后台地址:https://work.weixin.qq.com/

在这里插入图片描述
在这里插入图片描述

使用 Uniapp 开发 App 时,以下是一些需要注意的事项: 1. 跨平台适配:Uniapp 允许你使用一套代码同时开发多个平台的 App,如微信小程序、H5、App 等。但是需要注意不同平台的差异性,确保你的代码在各个平台上都能正常运行和展示。 2. 组件选择:Uniapp 提供了一些跨平台的组件,但并不是所有平台都支持所有组件。在选择组件时,要查看文档,了解组件在目标平台上的兼容性和限制。 3. 性能优化:App 的性能对用户体验至关重要。要注意减少不必要的请求、优化图片资源、减少页面渲染等方面来提高 App 的性能。 4. 适配不同屏幕尺寸:App 会在各种不同尺寸的设备上运行,要确保你的布局和样式能够适配不同的屏幕尺寸和分辨率。 5. 使用插件:Uniapp 提供了插件市场,可以使用各种插件来增加 App 的功能和特性。但是要注意选择可靠的插件,并且仔细查看插件文档和示例以确保正确使用。 6. 调试和测试:在开发过程中,及时进行调试和测试是非常重要的。Uniapp 提供了一些调试工具和模拟器,可以帮助你快速定位和解决问题。 7. 安全性考虑:App 的安全性是一个重要的问题。要注意保护用户的隐私数据,避免使用不安全的网络请求方式,以及对用户输入进行合理的验证和过滤。 8. 及时更新:Uniapp 是一个活跃的开源项目,会不断更新和改进。要及时关注 Uniapp 的更新和发布版本,并根据需要进行升级和迁移。 以上是一些开发 Uniapp App 需要注意的事项,希望对你有帮助!
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值