全能开发套餐,轻松打造现代网站!Vue3携手Vite带来开发新体验,结合Axios、Pinia、Element Plus实现功能与美观并重,TailwindCSS与DaisyUI提供设计灵活性,Router 4处理页面导航。从前端到后端,一站式解决!
一.创建项目(vue + js)
pnpm create vite
二.安装Axios 和 cookie
pnpm install axios
pnpm install js-cookie
1. 在根目录下创建.env.development 和 .env.production 文件
ENV = 'development'
VITE_BASE_URL='/api'
ENV = 'production'
VITE_BASE_URL = 'http://xxxxxx/api/'
2.修改packge.josn
"scripts": {
"dev": "vite --mode development",
"build": "vite build --mode production",
"preview": "vite preview"
},
2.在 src 文件下创建一个 config 文件夹,并添加 Api.js 文件(封装请求体)
import axios from 'axios'
import Cookies from "js-cookie";
let BASE_URL = import.meta.env.VITE_BASE_URL;
/**
* 参数转换
* @param result
* @returns {string}
*/
const queryParam =result=> {
let queryString = Object.keys(result)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(result[key])}`)
.join('&');
if (queryString.length >= 2) {
return '?' + queryString;
} else {
return '';
}
}
/**
* 构建请求体
* @param url
* @param method
* @param param
* @param query
*/
export const Ask =(url, method = 'GET', param = {}, query = {})=> {
return new Promise((resolve, reject) => {
try {
const config = {
url: BASE_URL + url + queryParam(query),
method,
data: param,
headers: {
'content-type': 'application/json',
'Authorization': "Bearer " + Cookies.get('token') || '',
}
};
axios(config)
.then(response => {
if (response.status === 200 || response.status === '200') {
resolve(response.data)
}else {reject(response)}
})
.catch(error => reject(error));
} catch (err) {
reject(err);
}
});
}
3.在 src 文件下创建一个 Interface文件夹(封装的接口文件夹)
例如:创建一个userApi.js 文件
import {Ask} from "../config/Api.js";
/**
* 登陆接口
*/
export function loginApi(param,query){
return Ask('/login','POST',param,query);
}
三. 安装状态管理器和数据持久化
pnpm install pinia
pnpm i pinia-plugin-persist
1.安装完 Pinia 包之后,需要在 main.js 文件中导入 createPinia 函数并将 Pinia 插件与 Vue 应用程序绑定
//main.js
import { createPinia } from 'pinia';
import piniaPersist from 'pinia-plugin-persist'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPersist)
2.在 src 文件下创建一个 store 文件夹,并添加 store.js 文件
import { defineStore } from 'pinia';
import axios from 'axios';
export const storeMange = defineStore(
'store',{
state: () => {
return{
menuList:[]
}
},
getters:{
getMenuList(){
return this.menuList;
}
},
actions:{
setMenuList() {
this.menuList=[2342]
}
},
persist: {
enabled:true,
strategies: [
{
storage: localStorage,
paths: ['menuList']
},
]
},
})
四.安装路由(通过接口设置动态路由),若您不需要,只需要index.js,删除addRouter()方法
pnpm add vue-router@4
1.在 src 文件下创建一个 router 文件夹,并添加 index.js 文件和routerTool.js文件
//router.js
import { createRouter, createWebHashHistory } from 'vue-router'
import {addRouter} from "./RouterTool.js";
const router = createRouter({
history: createWebHashHistory(),
routes: addRouter()
})
export default router
//routerTool.js
import {queryMenuApi} from "../Interface/system/menuApi.js";
import Cookies from "js-cookie";
let routers=[
{
name: 'index',
path: '/',
meta:{
name: '首页',
},
component:()=>import('../pages/frontWeb/index.vue'),
children:[]
}, {
name: 'admin',
path: '/admin',
component:()=>import('../pages/afterAdmin/index.vue'),
meta:{
name: '工作台',
},
children:[]
}
];
/**
* 菜单子集整合
*/
function childrenList(item,list){
let result =[];
list.map(item2=>{
if (item.id===item2.parentId){
item.children=childrenList(item2,list)
result.push(item2);
}
})
return result;
}
/**
* 菜单 整合
*/
export function routerMap(list){
let frontWebList = [];
let afterAdminList =[];
list.frontWeb.map((item)=>{
item.children=[];
if (item.parentId===0){
item.children=childrenList(item,list.frontWeb);
frontWebList.push(item);
}
});
list.afterAdmin.map((item)=>{
item.children=[];
if (item.parentId===0){
item.children=childrenList(item,list.afterAdmin);
afterAdminList.push(item);
}
});
return [frontWebList, afterAdminList];
}
/**
*router 整合
*/
function setRouter(lists=[]){
let routerList=[];
lists.map(item=>{
if (!item.isOutsidePath){
let routerObj ={
name: item.name,
path: item.path,
///* @vite-ignore */ 是消除警告
component: () => import(/* @vite-ignore */ "../pages/"+item.pagePath+".vue"),
meta:item.meta,
children:setRouter(item.children || [])
}
routerList.push(routerObj);
}
})
return routerList;
}
/**
* 添加router
*/
export function addRouter(){
queryMenuApi()
let routerList =routers;
let cookies = Cookies.get("menuList");
let cookList = cookies? JSON.parse(cookies) : [];
cookList.map((item,index)=>{
routerList[index].children=setRouter(cookList[index])
});
return routerList;
}
接口方法:(参考)
/**
* 获取菜单
*/
export function queryMenuApi(query){
Ask('/menu/query','GET',{},query).then(res=>{
if (res.code===200){
let list = routerMap(res.data) || [];
Cookies.set("menuList",JSON.stringify(list));
}
});
}
//返回字段解读
{
"id": 1,
"menuName": "菜单的名称",
"name": "router 的name",
"path": "router 的path",
"pagePath": "router 的component拼接路径",
"meta": {}, //meta 头
"isIcon": "",//选中图标地址 //(可选)
"noIcon": "",//未选中图标地址 //(可选)
"sort": 1,//菜单排序 //(可选)
"type": "",//菜单类型
"parentId": 0,//父级id(上一级的id,关联到router 的children[]) 默认是0
"createTime": "2024-08-07 14:51:56",//(可选)
"updateTime": "2024-08-07 14:51:56",//(可选)
"createUserName": "",//(可选)
"updateUserName": "",//(可选)
"purview": "",//菜单权限(可选)
"pageType": "" // 菜单分类 我分为前台router 和后台router () //"afterAdmin" 和"frontWeb"
}
接口返回数据例子
{
"code": 200,
"msg": "成功!",
"data": {
"afterAdmin": [],
"frontWeb": [
{
"id": 1,
"menuName": "测试数据",
"name": "test",
"path": "/",
"pagePath": "frontWeb/test",
"meta": {
"title": "测试页面"
},
"isIcon": "",
"noIcon": "",
"sort": 1,
"type": "page",
"parentId": 0,
"createTime": "2024-08-06 16:54:35",
"updateTime": "2024-08-06 16:54:35",
"createUserName": "小苏呀",
"updateUserName": "小苏呀",
"purview": "administrator",
"pageType": "frontWeb"
}
]
}
}
2.在main.js中引入
import router from './router/index.js'
app.use(router);
3.页面测试
App.vue
<style>
html,body{
height: 100%;
width: 100%;
}
</style>
<template>
<div>
<router-view/>
</div>
</template>
frontWeb/index.vue
<style scoped>
</style>
<template>
<div>
<div>111</div>
<router-view />
</div>
</template>
<script setup>
</script>
运行项目示例
五.安装 element-plus
pnpm install element-plus
pnpm install -D unplugin-vue-components unplugin-auto-import
1.vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
vue(),
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
server: {
open:true,
host: '0.0.0.0',
port: 3001,
}
})
2.安装图标
pnpm install @element-plus/icons-vue
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia';
import piniaPersist from 'pinia-plugin-persist'
import router from './router/index.js'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
const pinia = createPinia()
pinia.use(piniaPersist)
app.use(pinia);
app.use(router);
app.mount('#app');
测试:
<div>
<el-button type="primary" :icon="Edit" />
<el-button type="primary" :icon="Share" />
<el-button type="primary" :icon="Delete" />
<el-button type="primary" :icon="Search">Search</el-button>
<el-button type="primary">
Upload<el-icon class="el-icon--right"><Upload /></el-icon>
</el-button>
</div>
六.安装Tailwind CSS 和 daisyUI
pnpm add -D daisyui@latest
pnpm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
1.修改一下tailwind.config
配置文件,修改成下面这样的
/** @type {import('tailwindcss').Config} */
import daisyui from "daisyui";
module.exports = {
content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
theme: {
extend: {},
},
plugins: [daisyui],
}
3.在style.css 文件添加样式
//全部替换或者添加
@tailwind base;
@tailwind components;
@tailwind utilities;
4.测试
<div class="button-container flex justify-center my-10">
<button class="btn">Button</button>
<button class="btn btn-primary">Button</button>
<button class="btn btn-secondary">Button</button>
<button class="btn btn-accent">Button</button>
<button class="btn btn-ghost">Button</button>
<button class="btn btn-link">Button</button>
</div>
运行后效果
所有安装教程就到这了,有更好就方式,私信小编!!!!
需要前端+后端配套源码私信小编,附带测试数据库
推荐程序网站:
天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/