创建vite项目
看文档去,按操作提示来
// 快速创建项目,不建议这么用
npm install vite@lastest my-project
引入element-plus
看文档去,最好选择按需导入的自动导入。别问为什么,问就是我的完整引入用不了。
使用包管理器安装 Element Plus:
npm install element-plus --save
全局导入:
import Element-plus from 'element'
import 'element-plus/dist/index.css'
createApp(App).use(ElementPlus)
按需导入:
// 安装`unplugin-vue-components` 和 `unplugin-auto-import`这两款插件
npm install -D unplugin-vue-components unplugin-auto-import
// 配置vite.config.js
import { defineConfig } from 'vite'
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: [
// ...
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
}),
],
})
现在你就可以使用element的组件了
element plus的css样式有内置和自定义两种,可以直接写进标签里,如:
// border直接加上边框,
<el-table border ref="multipleTableRef" :data="tableData" style="width: 100%">
// 自定义style样式
<el-pagination
background
layout="prev, pager, next"
:total="1000"
style="display: flex; justify-content: center; margin-top: 10px;"
/>
vite的使用
- 配置ip、port、启动项目后自动打开浏览器,打包路径
// vite.config.ts
plugins: [
server: {
open: true, // 自动打开浏览器
host: "127.0.0.1",
port: 3001
}
base: './' // 打包相对路径
]
-
安装多个需要的依赖
npm i axios vuex vue-router -
各个文件夹的作用
-
安装sass
npm install sass剩下步骤百度去 -
安装路由router
安装依赖
// 查看版本号
npm view vue-router version
// 没有就下载一下
pnpm install vue-router@4
创建router/index.ts
// src/router/index.js
import { createRouter,createWebHistory } from 'vue-router'
import ComponentA from '../views/ComponentA.vue'
const routes = [
{
path: '/',
name: 'componentA',
component: ComponentA
},
{
path: '/componentB',
name: 'componentB',
component: ()=> import("../views/ComponentB.vue")
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
在main.ts里使用
// main.ts
import router from './router/index.js'
app.use(router)
在需要的组件里放入<router-view></router-view>来使用
- 安装状态管理文件store
创建store/index.ts
// store/index.ts
import { createStore } from 'vuex'
import admin from './admin'
export default createStore({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {
admin
}
})
在mian.ts使用
import store from './store'
.use(store)
- 安装axios
创建utill/axios.js
// util/axios.js
import axios from 'axios'
// 后端接口
const ConfigBaseURL = 'http://localhost:9999';
// 让ajax携带cookie(自动携带本地所有cookie)
axios.defaults.withCredentials = true;
// 使用create方法创建axios实例
const Service = axios.create({
baseURL: ConfigBaseURL, // 1.设置默认地址
timeout: 7000 // 2. 请求超时时间
})
// 3.给POST请求添加请求头设置(不同项目,值不一样)
Service.defaults.headers.post['Content-Type'] = 'applicatiion/json;charset=UTF-8'
// 4.1 添加请求拦截器
Service.interceptors.request.use(config =>{
return config
})
// 4.2 添加响应拦截器
Service.interceptors.response.use(response =>{
console.log("axios 的响应拦截")
return response
}, error => {
return Promise.reject(error)
})
export default Service;
要用session登录前端与后端的设置:session
在mian.ts使用
import axios from './axios'
.use(axios)
- 使用services
// services/admin.js
import axios from './../utils/axios'
// 获取管理员数据 根据页面与管理员姓名
function getAdminListBySearchAndPage({currentPage,pageSize,searchName}){
return axios({
url: "/getAdminListBySearchAndPage",
method: "post",
data:{
currentPage,
pageSize,
searchName
}
})
}
// 获取管理员总条数 根据页面与管理员姓名
function getAdminListBySearchCount({searchName}){
return axios({
url: "/getAdminListBySearchCount",
method: "post",
data:{
searchName
}
})
}
// 删除管理员
function delAdminById({id}){
return axios({
url: "/delAdminById",
method: "get",
params:{
id
}
})
}
// 获取管理员数据 根据管理员id
function getAdminInfoById({id}){
return axios({
url: "/ getAdminInfoById",
method: "get",
data:{
id
}
})
}
// 更新管理员数据 根据管理员id
function updateAdminInfoById({userInfo}){
return axios({
url: "/ updateAdminInfoById",
method: "post",
data: userInfo
})
}
// 添加管理员
function add_admin({user,pwd,rePwd,name,type}){
return axios({
url: "/ addAdmin",
method: "post",
data: {
user,pwd,rePwd,name,type
}
})
}
// 管理员登录
function add_login({user,pwd}){
return axios({
url: "/ add_login",
method: "post",
data: {
user,pwd
}
})
}
export default {
getAdminListBySearchAndPage,
getAdminListBySearchCount,
delAdminById,
getAdminInfoById,
updateAdminInfoById,
add_admin,
add_login
}
组装(可选)
// services/index.js
- 使用api管理地址
设置常量接口,方便管理
// api/admin.js
export const Get_AdminList_BySearchAndPage = './getAdminListBySearchAndPage'
export const GetAdminListBySearchCount = '/getAdminListBySearchCount'
... ...
统一暴露
// api/index.js
import * as admin from './admin' // 或者一个个引入:import {AddAdmin,XaYbb} from './admin'from
// 不能用import admin from './admin'来引入,因为admin.js没用export default
export default{
admin
}
暴露api接口后,要修改services/admin.js,引入api 并 将url地址替换
import api from './..api'
url: api.admin.GetAdminListBySearchAndPage,
- 使用hooks将业务内容独立出来
// hooks/admin.js
import { ElMessage } from "element-plus";
import AdminSearvice from "../services/admin"
import { useRouter } from "vue-router";
function Admin_Manage(){
const router = useRouter();
// 执行本函数返回对应的Admin相关操作
function Admin_Login(uesr,pwd){
AdminSearvice.admin_login(user,pwd).then((data)=>{
if(data.data.code == 200){
// 登录成功
ElMessage.success("登录成功");
// 跳转到首页
router.push("/home")
}else{
//data.msg 提示错误相关信息
ElMessage.warning(data.msg);
}
}).catch(err=>{
// err: 写入日志文件
console.log(err);
ElMessage.error("请求出错,请联系管理员")
});
}
function Add_Admin(){
}
function AdminListByPage(){
}
function AdminCountBySearchName(){
}
}
return {
Admin_Login,
Add_Admin,
AdminListByPage,
AdminCountBySearchName
}
export default { Admin_Manage }
然后在Login.vue中调用hooks中的方法
import Admin_Manage from '../hooks/admin'
const {Admin_Login} = Admin_Manage();
Admin_Login(user,pwd); // 执行登录方法
常见报错
错误一:(未解决) vue3.0+ts 找不到模块“./XXX.vue”或其相应的类型声明。
报错原因是:typescript只能理解 .ts 文件,无法理解 .vue文件
解决办法:(然而我的为什么没有效果?)
// src下创建一个.d.ts文件
declare module "*.vue" {
import { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}
错误二:(已解决) 打包后在 dist/index.html运行后页面为空;将代码部署到GitHub pages 时 dist/index.html页面为空白,控制台警告:Error with Permissions-Policy header: Origin trial controlled feature not enabled: 'interest-cohort'.
报错原因:
- router配置应该用hash而不是history
- base未设置服务器路径
解决方法:
- 将router改为hash
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
// 省略。。。。
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
- 如果是在本地运行,base改为
base: './'
如果是在github pages,base改为 base: '/repos/dist'
项目经验:
1. $ref代替ref (此方法未成功,报错,待纠正)
vue3的响应式数据ref对象在使用时需要加value很麻烦,因此我们使用vue3的语法糖 ---> $ref,这样就不用加value。
但是$ref不能用watch监听了
// vite.config.js
export default defineConfig({
plugins: [
vue({
refTranslaform: true, // 启用响应式语法糖$ref $computed $toRef
reactivityTransform: true
}),
],
})
2. 将element的分散两个button按钮放在一块 给两个按钮加个div就好了(query-box布局为display: flex; justify-content: space-between;)
<div class="query-box">
<el-input class="queryInput" v-model="queryInput" placeholder="请输入姓名搜索" />
<div class="btnList">
<el-button type="primary" @click="handleAdd">增加</el-button>
<el-button type="danger" @click="handleDelList">删除多选</el-button>
</div>
</div>
3. 绑定多个事件,函数嵌套?
源代码
整了这么多业务逻辑的代码,是不是很想看源代码?
只可惜这个项目没有后端接口,逻辑代码也有错误,所以在原来的基础上给你加一个简单的看,它实现了login,home的纯静态页面