Uniapp Vue3/Vite Typescript
命令安装
npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project
vscode 快速开发插件
- uni-create-view
快速创建 uniapp 视图与组件!
配置
@ext:mrmaoddxxaa.create-uniapp-view
- uni-helper
uniapp 代码提示
- uniapp 小程序扩展
鼠标悬浮在 api 上面会提示文档
ts 类型校验
校验属性值错误提示
pnpm add -D @types/wechat-miniprogram @uni-helper/uni-app-types
tsconfig.json
{
"compilerOptions": {
"types": ["@dcloudio/types", "node", "@uni-helper/uni-app-types"],
"ignoreDeprecations": "5.0"
},
"vueCompilerOptions": { "nativeTags": ["block", "component", "template", "slot"] },
}
vscode 允许 manifest.json 等文件注释
files.associations
pnpm add @types/uni-app -D
pnpm add @types/uni-app -D
获取安全距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// {top: 20, left: 0, right: 0, bottom: 0}
console.log(11, safeAreaInsets);
使用 onLoad 等生命周期
import { onLoad } from "@dcloudio/uni-app";
onLoad(() => {});
- 传参,接收参数
// 传参
uni.navigateTo({ url: '/member/setting/setting?id=1' });
<script lang="ts" setup>
// 接收参数一
onLoad(e => {
console.log(e);
});
// 接收参数二 vue3中写法
const props = defineProps<{ id: number }>();
console.log('🚀 ~ props:', props);
</script>
使用分包和预下载
优化小程序的下载和启动速度
在 pages
同级目录下新建 member
目录
pages.json
// 分包加载配置
"subPackages": [
{
// 子包的根目录
"root": "member",
// 子包由哪些页面组成,参数同 pages
"pages": [
{
"path": "setting/setting",
"style": {
"navigationBarTitleText": "设置"
}
}
]
}
],
// 分包预下载规则
"preloadRule": {
// 在我的页面进入会员分包模块,预下载
"pages/mine/mine": {
// 在指定网络下预下载,可选值为:all(不限网络)、wifi(仅wifi下预下载)
"network": "all",
// 进入页面后预下载分包的 root 或 name。__APP__ 表示主包。
"packages": ["member"]
}
}
路由分包跳转
uni.navigateTo({ url: '/member/setting/setting' });
环境变量
const DOMAIN = {
development: 'http://127.0.0.1:3000',
test: '',
production: '',
};
let BASE_URL = '';
// #ifdef H5
if (process.env.NODE_ENV === 'development') {
BASE_URL = DOMAIN.development;
} else if (process.env.NODE_ENV === 'production') {
BASE_URL = DOMAIN.production;
}
// #endif
// #ifdef MP-WEIXIN
const envVersion = uni.getAccountInfoSync()?.miniProgram?.envVersion;
if (envVersion === 'develop') {
BASE_URL = DOMAIN.development;
} else if (envVersion === 'trial') {
BASE_URL = DOMAIN.production;
} else if (envVersion === 'release') {
BASE_URL = DOMAIN.production;
}
// #endif
使用 pinia
pnpm add pinia@2.0.33
src/main.ts
import { createSSRApp } from "vue";
import * as Pinia from "pinia";
export function createApp() {
const app = createSSRApp(App);
app.use(Pinia.createPinia());
return {
app,
Pinia, // 此处必须将 Pinia 返回
};
}
src/stores/counter.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => {
return { count: 0 };
},
// 也可以这样定义
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++;
},
},
});
使用
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
pinia 持久化
- 安装
pnpm i pinia-plugin-persistedstate
- 配置
const pinia = Pinia.createPinia();
pinia.use(piniaPluginPersistedstate);
- 使用
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => {
return { count: 0 };
},
persist: {
// 改为 uni 写法
storage: {
getItem: (key) => {
return uni.getStorageSync(key);
},
setItem: (key, value) => uni.setStorageSync(key, value),
},
},
});
crypto-js
报错 Native crypto module could not be used to get secure random number.
下载指定版本
pnpm add crypto-js@3.3.0
import CryptoJS from 'crypto-js';
const CRYPTO_SECRET = '__abc__';
/**
* 加密数据
* @param data - 数据
*/
export function encrypt(data: any) {
const json = JSON.stringify(data);
return CryptoJS.AES.encrypt(json, CRYPTO_SECRET).toString();
}
/**
* 解密数据
* @param cipherText - 密文
*/
export function decrypt(cipherText: string) {
const bytes = CryptoJS.AES.decrypt(cipherText, CRYPTO_SECRET);
const originalText = bytes.toString(CryptoJS.enc.Utf8);
if (originalText) {
return JSON.parse(originalText);
}
return null;
}
使用 unocss
兼容小程序 unocss-preset-weapp
pnpm add unocss unocss-preset-weapp -D
vite.config.ts
import { defineConfig } from 'vite'
import uni from '@dcloudio/vite-plugin-uni'
import Unocss from 'unocss/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
uni(),
// https://github.com/antfu/unocss
Unocss(),
],
})
uno.config.ts
import presetWeapp from 'unocss-preset-weapp';
import { extractorAttributify, transformerClass } from 'unocss-preset-weapp/transformer';
const { presetWeappAttributify, transformerAttributify } = extractorAttributify();
export default {
presets: [
// https://github.com/MellowCo/unocss-preset-weapp
presetWeapp(),
// attributify autocomplete
presetWeappAttributify(),
],
shortcuts: [
{
'border-base': 'border border-gray-500_10',
center: 'flex justify-center items-center',
},
],
theme: {
colors: {
primary: '#186ffc',
},
},
transformers: [
// https://github.com/MellowCo/unocss-preset-weapp/tree/main/src/transformer/transformerAttributify
transformerAttributify(),
// https://github.com/MellowCo/unocss-preset-weapp/tree/main/src/transformer/transformerClass
transformerClass(),
],
};
main.ts
import 'uno.css'