vue3开发景德镇当地特色浏览网站(小程序版)

1,578 阅读2分钟

把之前h5端的页面,迁移到小程序(uni-app)了,并使用koa单独开发后端,使用mysql存储数据,现在能更灵活的CURD数据了。源码地址

💓🥰Younglina🌻😸 2023-11-11 16.04.58.gif

记录一下迁移uni-app的一些配置和使用

创建vue3的项目模板

官网说明

npx degit dcloudio/uni-preset-vue#vite my-vue3-project //选择默认模板

pnpm i //安装好依赖

npm run dev:mp-weixin // 编译运行微信小程序

执行完上面的操作以后,根目录下会生成一个dist/dev/mp-weixin文件夹,使用微信开发者工具打开这个文件夹即可看到效果,直接修改代码是可以实时热编译的,如果不行,手动刷新(手动狗头

创建页面

官网说明

页面路由就直接用自带的pages,在src/pages.json中配置pages参数,默认数组中第一个为入口页

"pages": [
	{
		"path": "pages/index/index",
		"style": {
			"navigationBarTitleText": "首页"
			}
	},
]

页面的代码统一在src/pages文件夹下编写

tabBar

官网说明

src/pages.json中配置tabBar参数,对应的icon直接存放在static文件夹下即可

"tabBar": {
	"list": [
		{
			"pagePath": "pages/index/index",
			"text": "首页",
			"iconPath": "static/home.png",
			"selectedIconPath": "static/home_active.png"
		},
	]
}

路由

官网说明

路由直接用自带的即可。

uni.navigateTo

保留当前页面,跳转到应用内的某个页面,使用uni.navigateBack可以返回到原页面。

uni.reLaunch(OBJECT)

关闭所有页面,打开到应用内的某个页面。

uni.redirectTo

关闭当前页面,跳转到应用内的某个页面。

uni.switchTab(OBJECT)

跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。

获取路由参数

跳转时直接在路径后面拼接即可,如果参数很多,可以使用全局事件pinia

// 跳转
const toView = (item) => {
	uni.navigateTo({url: `/pages/area-card/index?dataType=${item.value}&typeStr=${item.text}`})
}
// 接收参数
import { onload } from 'uni-app'

onload((options)=>{
	// 都在options中
	options.dataType
})

pinia持久化

pnpm i pinia@2.0.33 pinia-plugin-unistorage

main.js中引用

import { createSSRApp } from "vue";
import { createPinia } from 'pinia'
import { createUnistorage } from 'pinia-plugin-unistorage'
import App from "./App.vue";

export function createApp() {
	const app = createSSRApp(App);
	const pinia = createPinia()
	pinia.use(createUnistorage());
	app.use(pinia)
	return {
		app,
		pinia
	};
}

src目录下新建store/index.js

import { defineStore } from 'pinia'

export const useStore = defineStore('wyStore', {
	// 使用持久化
	unistorage: true,
	...
}

使用

import { useStore } from '@/store'
const store = useStore()

store...

自定义vue组件

当需要自定义组件时,统一在src/components文件夹下创建,在需要使用的地方引入即可。

import CommentList from '@/components/CommentList/CommentList.vue'

静态文件

存放在src/static下,使用时引入对应路径即可

<image src="@/static/empty.png"></image>

封装请求

封装uni.request统一管理

const BASE_URL = "http://localhost:3001/api"

const baseRequest = async (url, method, data = {}) => {
	let header = {}
	return new Promise((reslove, reject) => {
		uni.request({
			url: BASE_URL + url,
			method: method || 'GET',
			header: header,
			timeout: 10000,
			withCredentials: true,
			data: data || {},
			success: (successData) => {
				const res = successData.data
				if (successData.statusCode == 200) {
					reslove(res.data)
				} else {
					reject(res)
				}
			},
			fail: (msg) => {
				reject(msg)
			}
		})
	})
}

const request = {}
const methods = ['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect']
methods.map((item) => {
	request[item] = (api, data) => baseRequest(api, item, data)
})

export default request