Uniapp中使用vue3语法

在setup语法糖中调用uniapp的页面生命周期

<script setup>
	import { onShow } from "@dcloudio/uni-app"
	onShow(() => {
		//hanlder...
	})
</script>

vue2混入在vue3中建议使用组合式API

新建baseHook.js

import { ref } from "vue";
export function useBaseHook() {
	//响应式引入界面之后值变化 页面数据也会发生改变
	const userList = ref([])
	async function getUserList() {
		let requestRes = await request({
			//....
		})
		userList.value = requestRes.rows
	}
	return {
		userList,
		getUserList
	}
}

页面上使用

<script setup>
	import {useBaseHook} from '../utils/baseHook.js'
	let {userList,getUserList} = useBaseHook()
</script>

状态管理Pinia

uniapp教程官网Pinia用法
HBuilder X 已内置了 Pinia,无需手动安装,按照下方示例使用即可。

main.js添加

import App from './App'
import { createSSRApp } from 'vue';
import * as Pinia from 'pinia';

export function createApp() {
	const app = createSSRApp(App);
	app.use(Pinia.createPinia());
	return {
		app,
		Pinia, // 此处必须将 Pinia 返回
	};
}

创建一个 Store

// stores/counter.js
import { defineStore } from 'pinia';

export const useCounterStore = defineStore('counter', {
	const count = ref(0);
	function increment() {
		count.value++;
	}

	return { count, increment };
});

页面使用

<script setup>
	import { useCounterStore } from '@/stores/counter'
	const counter = useCounterStore()
	counter.count++
	
	counter.$patch({ count: counter.count + 1 })
	// 或使用 action 代替
	counter.increment()
</script>
<template>
  <!-- 直接从 store 中访问 state -->
  <div>Current Count: {{ counter.count }}</div>
</template>

页面跳转、传值在setup语法糖中(vue3)

跳转页

uni.navigateTo({
	url: "/pages/.../...",
	success: (e) => {
		e.eventChannel.emit('infoKey', 任意参数)
	}
})

接收页面

import { onShow,onLoad } from "@dcloudio/uni-app"
import { getCurrentInstance } from "vue";
const instance = getCurrentInstance().proxy
onLoad(() => {
	//或者onShow(() => {
	//在vue2语法中直接this.getOpenerEventChannel(),就能拿到eventChannel 
	//但是在vue3中好像没this的概念 用 getCurrentInstance().proxy代替了
	const eventChannel = instance.getOpenerEventChannel();
		eventChannel.on('infoKey', function(data) {
		console.log('infoKey', data)
	})
})

uniapp实现小程序全局分享

1.创建share,js

export default {
    created() {
        //#ifdef MP-WEIXIN
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
        //#endif
    },
}

2.main.js中直接引入

//引入分享
import share from './utils/share.js'
Vue.mixin(share)

全局网络请求的工具类改良版

// 'content-type' : "application/json" //这是最常用的
//form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)
// 'content-type': 'application/x-www-form-urlencoded'
//需要在表单中进行文件上传时,就需要使用该格式
// 'content-type' : 'multipart/form-data' 
export function requestM({
	url,
	method,
	data,
	isToken,
	noRuoYiCode200,
	contentType,
	addStr,
	noHeader,
	hideLoading,
}) {

	return new Promise((resolve, reject) => {
		if (!hideLoading) {
			uni.showLoading({
				title: "加载中...",
				mask: true,
			})
		}

		var header = {}
		if (!noHeader) {
			if (getToken()) header['Authorization'] = 'Bearer ' + getToken()
		}
		header['content-type'] = contentType ? contentType : "application/json;charset=UTF-8"
		var getInParams = data ? data : {};
		if (addStr) url = url + addStr
		try {
			//get请求时 请求体里面比较复杂比如:{params:{beginTIme:'2025-08-15', ...}}
			//规避后台接不到值
			if (!method || method == 'get' || method == 'GET') {
				header['content-type'] = "application/json, text/plain, */*"
				url = url + '?' + tansParams(getInParams);
				url = url.slice(0, -1);//去除url中的?
				getInParams = {}
			}
		} catch (e) {
			console.log(e, 'catch');
		}
		uni.request({
			url: url,
			method: method ? method : 'GET',
			timeout: 10000,
			data: getInParams,
			success: (e) => {
				// console.log(e, 'uni.reques');
				if (!hideLoading) uni.hideLoading()
				if (e.data.code == 200) {
					resolve(e.data || e.rows)
				} else if (e.data.code == 401) {
					console.log('in 401');
					clearCache()
					let mineStroe = useMineStore()
					mineStroe.resetAllRoles();
					uni.navigateTo({
						url: '/pages/login/login',
						success() {
							showToast('令牌过期,请重新登录!')
						}
					})
					reject(e)
				} else {
					console.log(e, 'requestM1');
					if (noRuoYiCode200) {
						if (e.data == '') {
							reject()
						} else {
							resolve(e.data)
						}
					} else {
						setTimeout(() => {
							showToast(e.data.msg)
						}, 600)
						reject(e)
					}
				}
			},
			header: header,
			fail: (e) => {
				if (!hideLoading) uni.hideLoading()
				console.log(e, 'requestM2');
				showToast(e.data && e.data.msg ? e.data.msg : '请求错误')
				setToken('')
				reject(e)
			},
			complete: () => {
				setTimeout(() => {
					if (!hideLoading) uni.hideLoading()
				}, 2000)
			}
		})
	})

}
/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName];
		var part = encodeURIComponent(propName) + "=";
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']';
						var subPart = encodeURIComponent(params) + "=";
						result += subPart + encodeURIComponent(value[key]) + "&";
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&";
			}
		}
	}
	return result
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值