一、用到的知识
- Vue3 compositionAPI
- Pinia / Pinia持久化处理
- Element Plus(表单校验,表格处理,组件封装)
- pnpm 包管理升级
- Eslint + prettier 更规范的配置
- husky(Git hooks工具):代码提交之前,进行校验
- 请求模块设计
- VueRouter4 路由设计
- AI 大模型开发一整个项目模块(掌握最新的开发方式)
- ······
二、大事件项目介绍和创建
在线演示:https://fe-bigevent-web.itheima.net/login
接口文档:https://apifox.com/apidoc/shared-26c67aee-0233-4d23-aab7-08448fdf95ff/api-93850835
基地址:http://big-event-vue-api-t.itheima.net
三、pnpm包管理器 - 创建项目
优势:比同类工具快2倍左右、节省磁盘空间··· https://www.pnpm.cn/
安装方式:
npm install -g pnpm
创建项目:
pnpm create vue
常用命令:
npm | yarn | pnpm |
npm install | yarn | pnpm install |
npm install axios | yarn add axios | pnpm add axios |
npm install axios -D | yarn add axios -D | pnpm add axios -D |
npm uninstall axios | yarn remove axios | pnpm remove axios |
npm run dev | yarn dev | pnpm dev |
四、Eslint配置代码风格
配置文件:.eslintrc.cjs
1. prettier 风格配置 https://prettier.io
2. vue组件名称多单词组成(忽略index.vue)
3. props解构(关闭)
/* eslint-env node */
require('@rushstack/eslint-patch/modern-module-resolution')module.exports = {root: true,'extends': ['plugin:vue/vue3-essential','eslint:recommended','@vue/eslint-config-prettier/skip-formatting'],parserOptions: {ecmaVersion: 'latest'},rules: {// prettier专注于代码的美观度 (格式化工具)// 前置:// 1. 禁用格式化插件 prettier format on save 关闭// 2. 安装Eslint插件, 并配置保存时自动修复'prettier/prettier': ['warn',{singleQuote: true, // 单引号semi: false, // 无分号printWidth: 80, // 每行宽度至多80字符trailingComma: 'none', // 不加对象|数组最后逗号endOfLine: 'auto' // 换行符号不限制(win mac 不一致)}],// ESLint关注于规范, 如果不符合规范,报错'vue/multi-word-component-names': ['warn',{ignores: ['index'] // vue组件名称多单词组成(忽略index.vue)}],'vue/no-setup-props-destructure': ['off'], // 关闭 props 解构的校验 (props解构丢失响应式)// 添加未定义变量错误提示,create-vue@3.6.3 关闭,这里加上是为了支持下一个章节演示。'no-undef': 'error'}
}
前提条件:安装Eslint插件且配置保存修复,不要开启默认的自动保存格式化,把Prettier - Code formatter插件禁用。
settings.json
{"workbench.colorTheme": "Default Light+","[html]": {"editor.defaultFormatter": "vscode.html-language-features"},"emmet.triggerExpansionOnTab": true,// "[vue]": {// "editor.defaultFormatter": "Vue.volar"// },// 当保存的时候,eslint自动帮我们修复错误"editor.codeActionsOnSave": {"source.fixAll": "explicit"},// 保存代码,不自动格式化"editor.formatOnSave": false
}
五、配置代码检查工作流
1. 提交前做代码检查
1. 打开git bash终端,初始化git仓库,执行 git init 即可
2. 初始化husky工具配置,执行 pnpm dlx husky-init && pnpm install 即可
https://typicode.github.io/husky/
3. 修改 .husky/pre-commit文件
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"pnpm lint
4. 提交测试
5. 问题:pnpm lint 是全量检查,耗时问题,历史问题
2. 暂存区eslint校验
1. 安装lint-staged包
pnpm i lint-staged -D
2. package.json配置lint-staged命令
{······"prepare": "husky install","lint-staged": "lint-staged"},······"devDependencies": {······},"lint-staged": {"*.{js,ts,vue}": ["eslint --fix"]}
}
3. .husky/pre-commit文件修改
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"pnpm lint-staged
六、目录调整
默认生成的目录结构不满足我们的开发需求,所以这里需要做一些自定义改动。
主要是以下工作:
1. 删除一些初始化的默认文件
清空assets、components、store、views文件夹下的内容;
2. 修改剩余代码内容
①router/index.js
import { createRouter, createWebHistory } from 'vue-router'const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),routes: []
})export default router
②App.vue
<script setup></script><template><div>我是App</div>
</template><style scoped></style>
③main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'import App from './App.vue'
import router from './router'const app = createApp(App)app.use(createPinia())
app.use(router)app.mount('#app')
3. 新增调整我们需要的目录结构
在src下新增utils和api文件夹。
4. 拷贝全局样式和图片,安装 sass预处理器 支持
pnpm add sass -D
5. 启动项目
pnpm dev
七、vue-router4路由代码解析
1. 路由初始化
1. 创建路由实例由 createRouter 实现
2. 路由模式
- ①history模式使用createWebHistory()
- ②hash模式使用createWebHashHistory()
- ③参数是基础路径,默认/
Vite官网:环境变量和模式 | Vite 官方中文文档
八、引入Element Plus组件库
1. 按需引入Element Plus
1. 安装
pnpm add element-plus
2. 配置按需导入
官方文档:https://element-plus.org/zh-CN/guide/quickstart.html
①首先,安装unplugin-vue-components
和 unplugin-auto-import
这两款插件
pnpm add -D unplugin-vue-components unplugin-auto-import
②修改配置文件:vite.config.js
import { fileURLToPath, URL } from 'node:url'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'// https://vitejs.dev/config/
export default defineConfig({// base: '/jd',plugins: [vue(),AutoImport({resolvers: [ElementPlusResolver()]}),Components({resolvers: [ElementPlusResolver()]})],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url))}}
})
3. 直接使用组件(组件内自动按需导入)
components/TestDemo.vue
<template><div>我是test测试的组件</div>
</template>
App.vue
<script setup>
// 在Vue3 CompositionAPI中
// 1. 获取路由对象router useRouter
// const router = useRouter
// 2. 获取路由参数 route useRoute
// const route = useRoute()
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const goList = () => {// this.$router.push('/list') // this指向undefinedconsole.log(router, route)router.push('/list')
}
</script><template>我是App<!-- 组件名要符合规范才可以自动按需导入 --><test-demo></test-demo><el-button @click="$router.push('/home')">跳首页</el-button><el-button @click="goList">跳列表页</el-button><el-button type="primary">Primary</el-button><el-button type="success">Success</el-button>
</template><style scoped></style>
4. 彩蛋:默认components下的文件也会被自动注册
九、Pinia构建仓库和持久化
(1)持久化
①src/store/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'// 用户模块 token setToken removeToken
export const useUserStore = defineStore('big-user', () => {const token = ref('')const setToken = (newToken) => {token.value = newToken}const removeToken = () => {token.value = ''}return {token,setToken,removeToken}
})
②App.vue
<script setup>
// 在Vue3 CompositionAPI中
// 1. 获取路由对象router useRouter
// const router = useRouter
// 2. 获取路由参数 route useRoute
// const route = useRoute()
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()
const goList = () => {// this.$router.push('/list') // this指向undefinedconsole.log(router, route)router.push('/list')
}import { useUserStore } from './stores/user'
const userStore = useUserStore()
</script><template><div>我是App<!-- 组件名要符合规范才可以自动按需导入 --><test-demo></test-demo><el-button @click="$router.push('/home')">跳首页</el-button><el-button @click="goList">跳列表页</el-button><el-button type="primary">Primary</el-button><el-button type="success">Success</el-button><p>{{ userStore.token }}</p><el-button @click="userStore.setToken('Bearersidhfklamvj')">登录</el-button><el-button @click="userStore.removeToken('')">退出</el-button></div>
</template><style scoped></style>
③持久化
pnpm add pinia-plugin-persistedstate -D
④使用main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'
import App from './App.vue'
import router from './router'
import '@/assets/main.scss'const app = createApp(App)app.use(router)
app.use(createPinia().use(persist))app.mount('#app')
⑤在store/user.js中添加第三个参数persist
import { defineStore } from 'pinia'
import { ref } from 'vue'// 用户模块 token setToken removeToken
export const useUserStore = defineStore('big-user',() => {const token = ref('')const setToken = (newToken) => {token.value = newToken}const removeToken = () => {token.value = ''}return {token,setToken,removeToken}},{persist: true}
)
(2)Pinia仓库统一管理
目标:pinia独立维护,仓库统一导出
①src/stores/index.js
import { createPinia } from 'pinia'
import persist from 'pinia-plugin-persistedstate'const pinia = createPinia()
pinia.use(persist)export default pinia// import { useUserStore } from './modules/user'
// import { useCounterStore } from './modules/counter'
// export { useUserStore, useCounterStore }export * from './modules/user' // 接收user模块的所有按需导出
export * from './modules/counter'
②main.js
import { createApp } from 'vue'
import pinia from '@/stores/index'
import App from './App.vue'
import router from './router'
import '@/assets/main.scss'const app = createApp(App)app.use(router)
app.use(pinia)app.mount('#app')
③App.vue
<script setup>
// 在Vue3 CompositionAPI中
// 1. 获取路由对象router useRouter
// const router = useRouter
// 2. 获取路由参数 route useRoute
// const route = useRoute()
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useCounterStore } from './stores'const router = useRouter()
const route = useRoute()
const goList = () => {// this.$router.push('/list') // this指向undefinedconsole.log(router, route)router.push('/list')
}const userStore = useUserStore()
const counterStore = useCounterStore()
</script><template><div>我是App<!-- 组件名要符合规范才可以自动按需导入 --><test-demo></test-demo><el-button @click="$router.push('/home')">跳首页</el-button><el-button @click="goList">跳列表页</el-button><el-button type="primary">Primary</el-button><el-button type="success">Success</el-button><p>{{ userStore.token }}</p><el-button @click="userStore.setToken('Bearersidhfklamvj')">登录</el-button><el-button @click="userStore.removeToken('')">退出</el-button><p>{{ counterStore.count }}</p><el-button @click="counterStore.sub(1)">-</el-button><el-button @click="counterStore.add(1)">+</el-button></div>
</template><style scoped></style>
十、数据交互 - 请求工具设计
①安装axios
②请求配置
拦截器 | Axios中文文档 | Axios中文网
src/utils/request.js
import axios from 'axios'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import router from '@/router'const baseURL = 'http://big-event-vue-api-t.itheima.net'const instance = axios.create({// TODO 1. 基础地址,超时时间baseURL,timeout: 10000
})// 请求拦截器
instance.interceptors.request.use((config) => {// TODO 2. 携带tokenconst useStore = useUserStore()if (useStore.token) {config.headers.Authorization = useStore.token}return config},(err) => Promise.reject(err)
)// 响应拦截器
instance.interceptors.response.use((res) => {// TODO 4. 摘取核心响应数据if (res.data.code === 0) {return res}// TODO 3. 处理业务失败// 处理业务失败, 给错误提示,抛出错误ElMessage.error(res.data.message || '服务异常')return Promise.reject(res.data)},(err) => {// TODO 5. 处理401错误// 错误的特殊情况 => 401 权限不足 或 token 过期 => 拦截到登录if (err.response?.status === 401) {router.push('/login')}// 错误的默认情况 => 只要给提示ElMessage.error(err.response.data.message || '服务异常')return Promise.reject(err)}
)// 默认导出
export default instance
// 按需导出
export { baseURL }
十一、整体路由设计
一级路由:登录、架子
二级路由:文章分类、文章管理、基本资料、更换头像、重置密码
router/index.js
import { createRouter, createWebHistory } from 'vue-router'// createRouter 创建路由实例
// 1. createWebHistory 配置history模式 -> 地址栏不带#
// createWebHashHistory 配置hash模式 -> 地址栏带#// import.meta.env.BASE_URL vite中的环境变量,就是vite.config.js中的base配置项
const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),routes: [{ path: '/login', component: () => import('@/views/login/LoginPage.vue') }, // 登录页{path: '/',component: () => import('@/views/layout/LayoutContainer.vue'),redirect: '/article/manage',children: [{path: '/article/manage',component: () => import('@/views/article/ArticleManage.vue')},{path: '/article/channel',component: () => import('@/views/article/ArticleChannel.vue')},{path: '/user/profile',component: () => import('@/views/user/UserProfile.vue')},{path: '/user/avatar',component: () => import('@/views/user/UserAvatar.vue')},{path: '/user/password',component: () => import('@/views/user/UserPassword.vue')}]}]
})export default router
App.vue
<script setup>
// 在Vue3 CompositionAPI中
// 1. 获取路由对象router useRouter
// const router = useRouter
// 2. 获取路由参数 route useRoute
// const route = useRoute()
import { useRouter, useRoute } from 'vue-router'
import { useUserStore, useCounterStore } from './stores'const router = useRouter()
const route = useRoute()
const goList = () => {// this.$router.push('/list') // this指向undefinedconsole.log(router, route)router.push('/list')
}const userStore = useUserStore()
const counterStore = useCounterStore()
</script><template><div><hr /><router-view></router-view><hr /><hr /><hr />我是App<!-- 组件名要符合规范才可以自动按需导入 --><test-demo></test-demo><el-button @click="$router.push('/home')">跳首页</el-button><el-button @click="goList">跳列表页</el-button><el-button type="primary">Primary</el-button><el-button type="success">Success</el-button><p>{{ userStore.token }}</p><el-button @click="userStore.setToken('Bearersidhfklamvj')">登录</el-button><el-button @click="userStore.removeToken('')">退出</el-button><p>{{ counterStore.count }}</p><el-button @click="counterStore.sub(1)">-</el-button><el-button @click="counterStore.add(1)">+</el-button></div>
</template><style scoped></style>
在views下新建以下内容
十二、登录注册页面【Element-plus表单 & 表单校验】
功能需求说明:
1. 注册登录 静态结构 & 基本切换
2. 注册功能(校验 + 注册)
3. 登录功能(校验 + 登录 + 存token)
1. 注册登录 静态结构 & 基本切换
Typora破解中文版:https://pan.baidu.com/s/1F6bRpOLGoiBqnIlBIAdv2A
提取码:1234
①清空App.vue里的内容如下:
<script setup></script><template><router-view></router-view>
</template><style scoped></style>
②安装element-plus图标库
pnpm i @element-plus/icons-vue
③views/login/LoginPage.vue
<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
const isRegister = ref(true)
</script><template><el-row class="login-page"><el-col :span="12" class="bg"></el-col><el-col :span="6" :offset="3" class="form"><el-form ref="form" size="large" autocomplete="off" v-if="isRegister"><el-form-item><h1>注册</h1></el-form-item><el-form-item><el-input :prefix-icon="User" placeholder="请输入用户名"></el-input></el-form-item><el-form-item><el-input:prefix-icon="Lock"type="password"placeholder="请输入密码"></el-input></el-form-item><el-form-item><el-input:prefix-icon="Lock"type="password"placeholder="请输入再次密码"></el-input></el-form-item><el-form-item><el-button class="button" type="primary" auto-insert-space>注册</el-button></el-form-item><el-form-item class="flex"><el-link type="info" :underline="false" @click="isRegister = false">← 返回</el-link></el-form-item></el-form><el-form ref="form" size="large" autocomplete="off" v-else><el-form-item><h1>登录</h1></el-form-item><el-form-item><el-input :prefix-icon="User" placeholder="请输入用户名"></el-input></el-form-item><el-form-item><el-inputname="password":prefix-icon="Lock"type="password"placeholder="请输入密码"></el-input></el-form-item><el-form-item class="flex"><div class="flex"><el-checkbox>记住我</el-checkbox><el-link type="primary" :underline="false">忘记密码?</el-link></div></el-form-item><el-form-item><el-button class="button" type="primary" auto-insert-space>登录</el-button></el-form-item><el-form-item class="flex"><el-link type="info" :underline="false" @click="isRegister = true">注册 →</el-link></el-form-item></el-form></el-col></el-row>
</template><style lang="scss" scoped>
.login-page {height: 100vh;background-color: #fff;.bg {background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,url('@/assets/login_bg.jpg') no-repeat center / cover;border-radius: 0 20px 20px 0;}.form {display: flex;flex-direction: column;justify-content: center;user-select: none;.title {margin: 0 auto;}.button {width: 100%;}.flex {width: 100%;display: flex;justify-content: space-between;}}
}
</style>
2. 注册功能(校验 + 注册)
①src/views/login/LoginPage.vue
<script setup>
import { userRegisterService } from '@/api/user.js'
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
const isRegister = ref(true)
const form = ref()// 整个的用于提交的form数据对象
const formModel = ref({username: '',password: '',repassword: ''
})// 整个表单的校验规则
// 1. 非空校验 required: true message消息提示,trigger触发校验的时机:blur change
// 2. 长度校验 min:xxx, max:xxx
// 3. 正则校验 pattern: 正则规则 \S:非空字符
// 4. 自定义校验 => 自己写逻辑校验(校验函数)
// validator: (rule, value, callback)
// (1)rule: 当前校验规则的相关信息
// (2)value: 所校验的表单元素目前的表单值
// (3)callback 无论成功还是失败,都需要callback回调
// - callback()校验成功
// - callback(new Error(错误信息))校验失败
const rules = {username: [{ required: true, message: '请输入用户名', trigger: 'blur' },{ min: 5, max: 10, message: '用户名必须是5-10位的字符', trigger: 'blur' }],password: [{ required: true, message: '请输入密码', trigger: 'blur' },{pattern: /^\S{6,15}$/,message: '密码必须是6-15位的非空字符',trigger: 'blur'}],repassword: [{ required: true, message: '请输入密码', trigger: 'blur' },{pattern: /^\S{6,15}$/,message: '密码必须是6-15位的非空字符',trigger: 'blur'},{validator: (rule, value, callback) => {// 判断value和当前form中收集的password是否一致if (value !== formModel.value.password) {callback(new Error('两次输入的密码不一致'))} else {callback() // 即使校验成功,也需要callback}},trigger: 'blur'}]
}const register = async () => {// 注册成功之前,先进行校验。校验成功,请求;校验失败,自动提示await form.value.validate()// console.log('开始注册请求')await userRegisterService(formModel.value)// alert('注册成功')ElMessage.success('注册成功')isRegister.value = false
}
</script><template><!-- 1. 结构相关el-row表示一行,一行分成24份 el-col表示列 (1) :span="12" 代表在一行中,占12份 (50%)(2) :span="6" 表示在一行中,占6份 (25%)(3) :offset="3" 代表在一行中,左侧margin份数el-form 整个表单组件el-form-item 表单的一行 (一个表单域)el-input 表单元素(输入框)2. 校验相关(1) el-form => :model="ruleForm" 绑定的整个form的数据对象 { xxx, xxx, xxx }(2) el-form => :rules="rules" 绑定的整个rules规则对象 { xxx, xxx, xxx }(3) 表单元素 => v-model="ruleForm.xxx" 给表单元素,绑定form的子属性(4) el-form-item => prop配置生效的是哪个校验规则 (和rules中的字段要对应)--><el-row class="login-page"><el-col :span="12" class="bg"></el-col><el-col :span="6" :offset="3" class="form"><!-- 注册 --><el-form:model="formModel":rules="rules"ref="form"size="large"autocomplete="off"v-if="isRegister"><el-form-item><h1>注册</h1></el-form-item><el-form-item prop="username"><el-inputv-model="formModel.username":prefix-icon="User"placeholder="请输入用户名"></el-input></el-form-item><el-form-item prop="password"><el-inputv-model="formModel.password":prefix-icon="Lock"type="password"placeholder="请输入密码"></el-input></el-form-item><el-form-item prop="repassword"><el-inputv-model="formModel.repassword":prefix-icon="Lock"type="password"placeholder="请输入再次密码"></el-input></el-form-item><el-form-item><el-button@click="register"class="button"type="primary"auto-insert-space>注册</el-button></el-form-item><el-form-item class="flex"><el-link type="info" :underline="false" @click="isRegister = false">← 返回</el-link></el-form-item></el-form><!-- 登录 --></el-col></el-row>
</template>
②src/api/user.js
import request from '@/utils/request'// 注册接口
export const userRegisterService = ({ username, password, repassword }) =>request.post('/api/reg', { username, password, repassword })
③ .eslintrc.cjs
globals: {ElMessage: 'readonly',ElMessageBox: 'readonly',ElLoading: 'readonly'}
3. 登录功能(校验 + 登录 + 存token)
①src/views/login/LoginPage.vue
<script setup>
import { userRegisterService, userLoginService } from '@/api/user.js'
import { useUserStore } from '@/stores'
import { User, Lock } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
const isRegister = ref(false)
const form = ref()// 整个的用于提交的form数据对象
const formModel = ref({username: '',password: '',repassword: ''
})······const userStore = useUserStore()
const router = useRouter()// 登录
const login = async () => {await form.value.validate()// console.log('开始登录')const res = await userLoginService(formModel.value)// console.log(res)userStore.setToken(res.data.token)ElMessage.success('登录成功')router.push('/')
}// 切换时进行重置表单内容
watch(isRegister, () => {formModel.value = {username: '',password: '',repassword: ''}
})
</script><template><el-row class="login-page"><el-col :span="12" class="bg"></el-col><el-col :span="6" :offset="3" class="form"><!-- 注册 -->······<!-- 登录 --><el-form:model="formModel":rules="rules"ref="form"size="large"autocomplete="off"v-else><el-form-item><h1>登录</h1></el-form-item><el-form-item prop="username"><el-inputv-model="formModel.username":prefix-icon="User"placeholder="请输入用户名"></el-input></el-form-item><el-form-item prop="password"><el-inputv-model="formModel.password"name="password":prefix-icon="Lock"type="password"placeholder="请输入密码"></el-input></el-form-item><el-form-item class="flex"><div class="flex"><el-checkbox>记住我</el-checkbox><el-link type="primary" :underline="false">忘记密码?</el-link></div></el-form-item><el-form-item><el-button@click="login"class="button"type="primary"auto-insert-space>登录</el-button></el-form-item><el-form-item class="flex"><el-link type="info" :underline="false" @click="isRegister = true">注册 →</el-link></el-form-item></el-form></el-col></el-row>
</template>
②src/api/user.js
import request from '@/utils/request'// 注册接口
export const userRegisterService = ({ username, password, repassword }) =>request.post('/api/reg', { username, password, repassword })// 登录接口
export const userLoginService = ({ username, password }) =>request.post('/api/login', { username, password })
十三、首页layout架子【element-plus菜单组件】
功能需求说明:
1. 基本架子拆解(菜单组件的使用)
2. 登录访问拦截
3. 用户基本信息获取&渲染
4. 退出功能【element-plus确认框】
1. 基本架子拆解(菜单组件的使用)
Container 布局容器 | Element Plus
Menu 菜单 | Element Plus
①src/views/layout/LayoutContainer.vue
<script setup>
import {Management,Promotion,UserFilled,User,Crop,EditPen,SwitchButton,CaretBottom
} from '@element-plus/icons-vue'
import avatar from '@/assets/default.png'
</script><template><!--el-menu 整个菜单组件:default-active="$route.path" 配置默认高亮的菜单项router router选项开启,el-menu-item的index就是点击跳转的路径el-menu-item index="/article/channel" 配置的是访问的跳转路径,配合default-active的值实现高亮--><el-container class="layout-container"><el-aside width="200px"><div class="el-aside__logo"></div><el-menuactive-text-color="#ffd04b"background-color="#232323":default-active="$route.path"text-color="#fff"router><el-menu-item index="/article/channel"><el-icon><Management /></el-icon><span>文章分类</span></el-menu-item><el-menu-item index="/article/manage"><el-icon><Promotion /></el-icon><span>文章管理</span></el-menu-item><el-sub-menu index="/user"><!-- 多级菜单的标题 具名插槽title --><template #title><el-icon><UserFilled /></el-icon><span>个人中心</span></template><!-- 展开的内容 默认插槽 --><el-menu-item index="/user/profile"><el-icon><User /></el-icon><span>基本资料</span></el-menu-item><el-menu-item index="/user/avatar"><el-icon><Crop /></el-icon><span>更换头像</span></el-menu-item><el-menu-item index="/user/password"><el-icon><EditPen /></el-icon><span>重置密码</span></el-menu-item></el-sub-menu></el-menu></el-aside><el-container><el-header><div>黑马程序员:<strong>小帅鹏</strong></div><el-dropdown placement="bottom-end"><span class="el-dropdown__box"><el-avatar :src="avatar" /><el-icon><CaretBottom /></el-icon></span><template #dropdown><el-dropdown-menu><el-dropdown-item command="profile" :icon="User">基本资料</el-dropdown-item><el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item><el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item><el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></el-header><el-main><router-view></router-view></el-main><el-footer>大事件 ©2023 Created by 黑马程序员</el-footer></el-container></el-container>
</template><style lang="scss" scoped>
.layout-container {height: 100vh;.el-aside {background-color: #232323;&__logo {height: 120px;background: url('@/assets/logo.png') no-repeat center / 120px auto;}.el-menu {border-right: none;}}.el-header {background-color: #fff;display: flex;align-items: center;justify-content: space-between;.el-dropdown__box {display: flex;align-items: center;.el-icon {color: #999;margin-left: 10px;}&:active,&:focus {outline: none;}}}.el-footer {display: flex;align-items: center;justify-content: center;font-size: 14px;color: #666;}
}
</style>
2. 登录访问拦截
导航守卫 | Vue Router
src/router/index.js
import { useUserStore } from '@/stores'// 添加登录访问拦截 => 默认是直接放行的
// 根据返回值决定,是放行还是拦截
// 返回值:
// 1. undefined / true 直接放行
// 2. false 拦截回from的地址页面
// 3. 具体路径或路径对象 拦截到对应的地址
// '/login' { name: 'login' }
router.beforeEach(async (to) => {// 如果没有token,且访问的是非登录页,拦截到登录,其他情况正常放行const userStore = useUserStore()if (!userStore.token && to.path !== '/login') return '/login'// return true
})
3. 用户基本信息获取&渲染
①src/api/user.js
// 获取用户基本信息
export const userGetInfoService = () => request.get('/my/userinfo')
②src/stores/modules/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoService } from '@/api/user'// 用户模块 token setToken removeToken
export const useUserStore = defineStore('big-user',() => {const token = ref('')const setToken = (newToken) => {token.value = newToken}const removeToken = () => {token.value = ''}const user = ref({})const getUser = async () => {const res = await userGetInfoService()user.value = res.data.data}return {token,setToken,removeToken,user,getUser}},{persist: true}
)
③
<script setup>
······
import { useUserStore } from '@/stores'
import { onMounted } from 'vue'const userStore = useUserStore()onMounted(() => {userStore.getUser()
})
</script><template><el-container class="layout-container"><el-aside width="200px">// ······</el-aside><el-container><el-header><div>黑马程序员:<strong>{{userStore.user.nickname || userStore.user.username}}</strong></div><el-dropdown placement="bottom-end"><span class="el-dropdown__box"><el-avatar :src="userStore.user.user_pic || avatar" /><el-icon><CaretBottom /></el-icon></span>// ······</el-header>// ······</el-container>
</template><style lang="scss" scoped>
// ······
</style>
4. 退出功能【element-plus确认框】
①src/stores/modules/user.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userGetInfoService } from '@/api/user'// 用户模块 token setToken removeToken
export const useUserStore = defineStore('big-user',() => {// ······const user = ref({})const getUser = async () => {const res = await userGetInfoService()user.value = res.data.data}const setUser = (obj) => {user.value = obj}return {// ······user,getUser,setUser}},{persist: true}
)
②src/views/layout/LayoutContainer.vue
<script setup>
// ······
import { useRouter } from 'vue-router'const userStore = useUserStore()
const router = useRouter()// ······const handleCommand = async (key) => {if (key === 'logout') {// 退出操作await ElMessageBox.confirm('确认要进行退出吗?', '温馨提示', {confirmButtonText: '确认',cancelButtonText: '取消',type: 'warning'})// 清除本地的数据(token + user信息)userStore.removeToken()userStore.setUser({})router.push('/login')} else {// 跳转操作router.push(`/user/${key}`)}
}
</script><template><el-container class="layout-container">// ······<el-container><el-header><div>黑马程序员:<strong>{{userStore.user.nickname || userStore.user.username}}</strong></div><el-dropdown placement="bottom-end" @command="handleCommand"><!-- 展示给用户默认看到的 --><span class="el-dropdown__box"><el-avatar :src="userStore.user.user_pic || avatar" /><el-icon><CaretBottom /></el-icon></span><!-- 折叠的下拉部分 --><template #dropdown><el-dropdown-menu><el-dropdown-item command="profile" :icon="User">基本资料</el-dropdown-item><el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item><el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item><el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></el-header>// ······</el-container></el-container>
</template><style lang="scss" scoped>
// ······
}
</style>
十四、文章分类页面 - 【element-plus表格】
功能需求说明:
1. 基本架子 - PageContainer封装
2. 文章分类渲染 & loading处理
3. 文章分类添加编辑【element-plus弹层】
4. 文章分类删除
1. 基本架子 - PageContainer封装
①src/components/PageContainer.vue
<script setup>
defineProps({title: {required: true,type: String}
})
</script><template><el-card class="page-container"><template #header><div class="header"><span>{{ title }}</span><div class="extra"><!-- 具名插槽,定制额外的按钮 --><slot name="extra"></slot></div></div></template><!-- 默认插槽,定制内容 --><slot></slot></el-card>
</template><style lang="scss" scoped>
.page-container {min-height: 100%;box-sizing: border-box;.header {display: flex;align-items: center;justify-content: space-between;}
}
</style>
②src/views/article/ArticleChannel.vue
<template><page-container title="文章分类"><template #extra><el-button type="primary">添加分类</el-button></template>主体部分,是表格</page-container>
</template><style lang="scss" scoped></style>
③src/views/article/ArticleManage.vue
<template><page-container title="文章管理"><template #extra><el-button type="primary">添加文章</el-button></template>主体部分,是表格 + 分页</page-container>
</template><style lang="scss" scoped></style>
2. 文章分类渲染 & loading处理
(1)封装API - 请求获取表格数据
①新建src/api/article.js,封装接口获取频道列表的接口
import request from '@/utils/request'
// 获取文章分类
export const artGetChannelsService = () => request.get('/my/cate/list')
②页面中调用接口,获取数据存储 -> src/views/article/ArticleChannel.vue
这里默认应该是没有数据的,可以在在线演示系统,登录自己的账号添加数据:黑马程序员-大事件
<script setup>
import { ref } from 'vue'
import { artGetChannelsService } from '../../api/article'const channelList = ref([])const getChannelList = async () => {const res = await artGetChannelsService()channelList.value = res.data.data// console.log(channelList.value)
}// 一进页面,直接调用
getChannelList()
</script>
(2)el-table表格动态渲染
src/views/article/ArticleChannel.vue
<script setup>
import { ref } from 'vue'
import { artGetChannelsService } from '../../api/article'
import { Edit, Delete } from '@element-plus/icons-vue'const channelList = ref([])
const loading = ref(false)const getChannelList = async () => {// 发请求前开启loading效果loading.value = trueconst res = await artGetChannelsService()channelList.value = res.data.data// console.log(channelList.value)// 请求结束后关闭loading效果loading.value = false
}// 一进页面,直接调用
getChannelList()const onEditChannel = (row, $index) => {console.log(row, $index)
}
const onDelChannel = (row, $index) => {console.log(row, $index)
}
</script><template><page-container title="文章分类"><template #extra><el-button type="primary">添加分类</el-button></template><!-- v-loading绑定loading变量 --><el-table v-loading="loading" :data="channelList" style="width: 100%"><el-table-column type="index" label="序号" width="100"></el-table-column><el-table-column prop="cate_name" label="分类名称"></el-table-column><el-table-column prop="cate_alias" label="分类别名"></el-table-column><el-table-column prop="" label="操作" width="150"><!-- row 就是channelList的一项,$index是下标 --><template #default="{ row, $index }"><el-button:icon="Edit"circleplaintype="primary"@click="onEditChannel(row, $index)"></el-button><el-button:icon="Delete"circleplaintype="danger"@click="onDelChannel(row, $index)"></el-button></template></el-table-column><!-- 插槽 --><template #empty><el-empty description="没有数据" /></template></el-table></page-container>
</template><style lang="scss" scoped></style>
3. 文章分类添加编辑【element-plus弹层】
①封装组件 src/views/article/components/ChannelEdit.vue
<script setup>
import { ref } from 'vue'
const dialogVisible = ref(false)// 组件对外暴露一个方法open,基于open传来的参数,区分添加还是编辑
// open({}) => 表单无需渲染,说明是添加
// open({id, cate_name, ...}) => 表单需要渲染(数据回显),说明是编辑
// open调用后,可以打开弹窗const open = (row) => {console.log(row)dialogVisible.value = true
}// 向外暴露方法
defineExpose({open
})
</script>
<template><el-dialog v-model="dialogVisible" title="添加弹层" width="30%"><span>我是内容部分</span><template #footer><div class="dialog-footer"><el-button @click="dialogVisible = false">取消</el-button><el-button type="primary" @click="dialogVisible = false">确认</el-button></div></template></el-dialog>
</template>
②通过ref绑定,点击调用方法显示弹窗
src/views/article/ArticleChannel.vue
<script setup>
import { ref } from 'vue'
import { artGetChannelsService } from '../../api/article'
import { Edit, Delete } from '@element-plus/icons-vue'
import ChannelEdit from './components/ChannelEdit.vue'const channelList = ref([])
const loading = ref(false)
const dialog = ref()const getChannelList = async () => {// 发请求前开启loading效果loading.value = trueconst res = await artGetChannelsService()channelList.value = res.data.data// console.log(channelList.value)// 请求结束后关闭loading效果loading.value = false
}// 一进页面,直接调用
getChannelList()// 编辑
const onEditChannel = (row) => {dialog.value.open(row)
}
const onDelChannel = (row, $index) => {console.log(row, $index)
}// 添加
const onAddChannel = () => {// 显示弹层dialog.value.open({})
}
</script><template><page-container title="文章分类"><template #extra><el-button type="primary" @click="onAddChannel">添加分类</el-button></template><el-table v-loading="loading" :data="channelList" style="width: 100%"><el-table-column type="index" label="序号" width="100"></el-table-column><el-table-column prop="cate_name" label="分类名称"></el-table-column><el-table-column prop="cate_alias" label="分类别名"></el-table-column><el-table-column prop="" label="操作" width="150"><!-- row 就是channelList的一项,$index是下标 --><template #default="{ row, $index }"><el-button:icon="Edit"circleplaintype="primary"@click="onEditChannel(row, $index)"></el-button><el-button:icon="Delete"circleplaintype="danger"@click="onDelChannel(row, $index)"></el-button></template></el-table-column><!-- 插槽 --><template #empty><el-empty description="没有数据" /></template></el-table><ChannelEdit ref="dialog"></ChannelEdit></page-container>
</template><style lang="scss" scoped></style>
③准备弹层表单
准备表单和校验规则,编辑时回显
src/views/article/components/ChannelEdit.vue
<script setup>
import { ref } from 'vue'const dialogVisible = ref(false)
const formModel = ref({cate_name: '',cate_alias: ''
})
const rules = {cate_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' },{pattern: /^\S{1,10}$/,message: '分类名必须是1-10位的非空字符',trigger: 'blur'}],cate_alias: [{ required: true, message: '请输入分类别名', trigger: 'blur' },{pattern: /^[a-zA-Z0-9]{1,15}$/,message: '分类别名必须是1-15位的字母或数字',trigger: 'blur'}]
}// 组件对外暴露一个方法open,基于open传来的参数,区分添加还是编辑
// open({}) => 表单无需渲染,说明是添加
// open({id, cate_name, ...}) => 表单需要渲染(数据回显),说明是编辑
// open调用后,可以打开弹窗const open = (row) => {// console.log(row)dialogVisible.value = trueformModel.value = { ...row } // 添加-> 重置表单内容,编辑 -> 存储了需要回显的数据
}// 向外暴露方法
defineExpose({open
})
</script>
<template><el-dialogv-model="dialogVisible":title="formModel.id ? '编辑分类' : '添加分类'"width="30%"><el-form:model="formModel":rules="rules"label-width="100px"style="padding-right: 30px"><el-form-item prop="cate_name" label="分类名称"><el-inputv-model="formModel.cate_name"placeholder="请输入分类名称"></el-input></el-form-item><el-form-item prop="cate_alias" label="分类别名"><el-inputv-model="formModel.cate_alias"placeholder="请输入分类别名"></el-input></el-form-item></el-form><template #footer><div class="dialog-footer"><el-button @click="dialogVisible = false">取消</el-button><el-button type="primary" @click="dialogVisible = false">确认</el-button></div></template></el-dialog>
</template>
④确认提交 -> src/api/article.js,封装请求API
// 添加文章分类
export const artAddChannelsService = (data) =>request.post('/my/cate/add', data)
// 编辑文章分类
export const artEditChannelsService = (data) =>request.put('/my/cate/info', data)
⑤页面中校验,判断,提交请求
ChannelEdit.vue
import { artEditChannelsService, artAddChannelsService } from '@/api/article.js'const formRef = ref()
const emit = defineEmits(['success'])
const onSubmit = async () => {// 表单校验await formRef.value.validate()const isEdit = formModel.value.idif (isEdit) {// 编辑操作await artEditChannelsService(formModel.value)ElMessage.success('修改成功')} else {// 添加操作await artAddChannelsService(formModel.value)ElMessage.success('添加成功')}// 关闭弹层dialogVisible.value = false// 子传父emit('success')
}
⑥父组件监听success事件
<channel-edit ref="dialog" @success="onSuccess"></channel-edit>const onSuccess = () => {getChannelList()
}
4. 文章分类删除
①src/api/article.js
// 删除文章分类
export const artDelChannelsService = (id) =>request.delete('/my/cate/del', {params: { id }})
②ArticleChannel.vue
// 删除
const onDelChannel = async (row) => {await ElMessageBox.confirm('你确认要删除该分类么', '温馨提示', {type: 'warning',confirmButtonText: '确认',cancelButtonText: '取消'})await artDelChannelsService(row.id)ElMessage.success('删除成功')getChannelList()
}
十五、文章管理页面 - [element-plus进阶]
功能需求说明:
1. 文章列表渲染(带搜索 & 带分页)
2. 添加文章(抽屉 & 文件上传 & 富文本)
3. 编辑文章(共用抽屉)
4. 删除文章
1. 文章列表渲染(带搜索 & 带分页)
(1)文章列表渲染及基本架子搭建
①搜索表单
src/views/article/ArticleManage.vue
<template><page-container title="文章管理"><template #extra><el-button type="primary">添加文章</el-button></template><!-- 表单区域 --><el-form inline><el-form-item label="文章分类:"><el-select><!-- label是展示给用户看的,value是收集起来提交给后台的 --><el-option label="新闻" value="110"></el-option><el-option label="体育" value="137"></el-option></el-select></el-form-item><el-form-item label="发布状态:"><!-- 这里后台标记发布状态,就是通过中文标记的 --><el-select><el-option label="已发布" value="已发布"></el-option><el-option label="草稿" value="草稿"></el-option></el-select></el-form-item><el-form-item><el-button type="primary">搜索</el-button><el-button>重置</el-button></el-form-item></el-form><!-- 表格区域 --></page-container>
</template><style lang="scss" scoped></style>
②表格准备,模拟假数据渲染
<script setup>
import { Delete, Edit } from '@element-plus/icons-vue'
import { ref } from 'vue'
// 假数据
const articleList = ref([{id: 5961,title: '新的文章啊',pub_date: '2022-07-10 14:53:52.604',state: '已发布',cate_name: '体育'},{id: 5962,title: '新的文章啊',pub_date: '2022-07-10 14:54:30.904',state: '草稿',cate_name: '体育'}
])// 编辑
const onEditArticle = (row) => {console.log(row)
}// 删除
const onDeleteArticle = (row) => {console.log(row)
}
</script><template><page-container title="文章管理"><template #extra><el-button type="primary">添加文章</el-button></template><!-- 表单区域 --><el-form inline>// ······</el-form><!-- 表格区域 --><el-table :data="articleList" style="width: 100%"><el-table-column label="文章标题" width="400"><!-- 作用域插槽 --><template #default="{ row }"><el-link type="primary" :underline="false">{{ row.title }}</el-link></template></el-table-column><el-table-column label="分类" prop="cate_name"></el-table-column><el-table-column label="发表时间" prop="pub_date"> </el-table-column><el-table-column label="状态" prop="state"></el-table-column><!-- 利用作用域插槽,可用获取当前行的数据 --><el-table-column label="操作" width="100"><template #default="{ row }"><el-button:icon="Edit"circleplaintype="primary"@click="onEditArticle(row)"></el-button><el-button:icon="Delete"circleplaintype="danger"@click="onDeleteArticle(row)"></el-button></template></el-table-column><template #empty><el-empty description="没有数据" /></template></el-table></page-container>
</template><style lang="scss" scoped></style>
(2)中英国际化处理
全局配置 | Element Plus
默认是英文的,由于这里不涉及切换,所以在App.vue中直接导入设置成中文集合
App.vue
<script setup>
import zhCn from 'element-plus/es/locale/lang/zh-cn.mjs'
</script><template><!-- 路由出口 --><el-config-provider :locale="zhCn"><router-view></router-view></el-config-provider>
</template><style scoped></style>
(3)文章分类选择
①新建src/views/article/components/ChannelSelect.vue
<script setup>
import { artGetChannelsService } from '@/api/article.js'
import { ref } from 'vue'defineProps({modelValue: {type: [Number, String]}
})const emit = defineEmits(['update:modelValue'])
const channelList = ref([])
const getChannelList = async () => {const res = await artGetChannelsService()channelList.value = res.data.dataconsole.log(channelList.value)
}// 一进页面就调用
getChannelList()
</script><template><el-select:modelValue="modelValue"@update:modelValue="emit('update:modelValue', $event)"placeholder="请选择"size="large"style="width: 240px"><!-- label是展示给用户看的,value是收集起来提交给后台的 --><el-optionv-for="channel in channelList":key="channel.id":label="channel.cate_name":value="channel.id"></el-option></el-select>
</template>
②页面中导入渲染 - src/views/article/ArticleManage.vue
<script setup>
import { Delete, Edit } from '@element-plus/icons-vue'
import { ref } from 'vue'
import ChannelSelect from './components/ChannelSelect.vue'// 假数据
const articleList = ref([{id: 5961,title: '新的文章啊',pub_date: '2022-07-10 14:53:52.604',state: '已发布',cate_name: '体育'},{id: 5962,title: '新的文章啊',pub_date: '2022-07-10 14:54:30.904',state: '草稿',cate_name: '体育'}
])// 定义请求参数对象
const params = ref({pagenum: 1,pagesize: 5,cate_id: '',state: ''
})// 编辑
const onEditArticle = (row) => {console.log(row)
}// 删除
const onDeleteArticle = (row) => {console.log(row)
}
</script><template><page-container title="文章管理"><template #extra><el-button type="primary">添加文章</el-button></template><!-- 表单区域 --><el-form inline><el-form-item label="文章分类:"><!-- Vue2 => v-model :value和@input的简写 --><!-- Vue3 => v-model :modelValue 和 @update:modelValue的简写 --><channel-select v-model="params.cate_id"></channel-select></el-form-item><el-form-item label="发布状态:"><!-- 这里后台标记发布状态,就是通过中文标记的 --><el-selectv-model="params.state"placeholder="请选择"size="large"style="width: 240px"><el-option label="已发布" value="已发布"></el-option><el-option label="草稿" value="草稿"></el-option></el-select></el-form-item><el-form-item><el-button type="primary">搜索</el-button><el-button>重置</el-button></el-form-item></el-form><!-- 表格区域 --><el-table :data="articleList" style="width: 100%"><el-table-column label="文章标题" width="400"><!-- 作用域插槽 --><template #default="{ row }"><el-link type="primary" :underline="false">{{ row.title }}</el-link></template></el-table-column><el-table-column label="分类" prop="cate_name"></el-table-column><el-table-column label="发表时间" prop="pub_date"> </el-table-column><el-table-column label="状态" prop="state"></el-table-column><!-- 利用作用域插槽,可用获取当前行的数据 --><el-table-column label="操作" width="100"><template #default="{ row }"><el-button:icon="Edit"circleplaintype="primary"@click="onEditArticle(row)"></el-button><el-button:icon="Delete"circleplaintype="danger"@click="onDeleteArticle(row)"></el-button></template></el-table-column><template #empty><el-empty description="没有数据" /></template></el-table></page-container>
</template><style lang="scss" scoped></style>
(4)封装API接口,请求渲染
①src/api/article.js封装接口
// 文章:
// 获取文章列表
export const artGetListService = (params) =>request.get('/my/article/list', {params})
②ArticleMange.vue页面中调用保存数据
import { artGetListService } from '@/api/article.js'// 文章列表
const articleList = ref([])
// 总条数
const total = ref(0)// 基于params参数,获取文章列表
const getArticleList = async () => {const res = await artGetListService(params.value)articleList.value = res.data.datatotal.value = res.data.total
}
// 一进页面就调用
getArticleList()
③新建src/utils/format.js封装格式化日期函数
import { dayjs } from 'element-plus'export const formatTime = (time) => dayjs(time).format('YYYY年MM月DD日')
④ArticleMange.vue中调用
import { formatTime } from '@/utils/format.js'<el-table-column label="发表时间" prop="pub_date"><template #default="{ row }"><!-- 格式化时间 -->{{ formatTime(row.pub_date) }}</template>
</el-table-column>
(5)分页渲染[element-plus分页]
Pagination 分页 | Element Plus
①ArticleManage.vue
<script setup>
import { Delete, Edit } from '@element-plus/icons-vue'
import { ref } from 'vue'
import ChannelSelect from './components/ChannelSelect.vue'
import { artGetListService } from '@/api/article.js'
import { formatTime } from '@/utils/format.js'// ······// 处理分页
const onSizeChange = (size) => {// console.log('当前每页条数', size)// 只要是每页页数变化了,那么原本正在访问的当前页意义不大了,数据大概率已经不在原来那一页了// 重新从第一页开始渲染params.value.pagenum = 1params.value.pagesize = size// 基于最新的当前页和每页条数,渲染数据getArticleList()
}const onCurrentChange = (page) => {// console.log('当前每页条数', page)params.value.pagenum = page// 基于最新的当前页,渲染数据getArticleList()
}
</script><template><page-container title="文章管理"><template #extra><el-button type="primary">添加文章</el-button></template><!-- 表单区域 --><el-form inline>// ······</el-form><!-- 表格区域 --><el-table :data="articleList" style="width: 100%">// ······</el-table><!-- 分页区 --><el-paginationv-model:current-page="params.pagenum"v-model:page-size="params.pagesize":page-sizes="[2, 3, 5, 10]":background="true"layout="jumper, total, sizes, prev, pager, next":total="total"@size-change="onSizeChange"@current-change="onCurrentChange"style="margin-top: 20px; justify-content: flex-end"/></page-container>
</template><style lang="scss" scoped></style>
(6)添加loading效果
①准备数据
const loading = ref(false)
②el-table上面绑定
<el-table :data="articleList" v-loading="loading" style="width: 100%">
③发送请求添加loading
// 基于params参数,获取文章列表
const getArticleList = async () => {loading.value = trueconst res = await artGetListService(params.value)articleList.value = res.data.datatotal.value = res.data.totalloading.value = false
}
(7)搜索和重置功能
①注册事件
<el-form-item><el-button @click="onSearch" type="primary">搜索</el-button><el-button @click="onReset">重置</el-button>
</el-form-item>
②绑定处理
// 搜索逻辑 => 按照最新的条件,重新检索,从第一页开始展示
const onSearch = () => {params.value.pagenum = 1 // 重置页面getArticleList()
}// 重置逻辑 => 将筛选条件清空,重新检索,从第一页开始展示
const onReset = () => {params.value.pagenum = 1 // 重置页面params.value.cate_id = ''params.value.state = ''getArticleList()
}
2. 添加文章(抽屉 & 文件上传 & 富文本)
(1)点击显示抽屉
①准备数据
import { ref } from 'vue'
const visibleDrawer = ref(false)
②准备抽屉容器
<!-- 抽屉区 -->
<el-drawerv-model="visibleDrawer"title="大标题"direction="rtl"size="50%"
><span>Hi there!</span>
</el-drawer>
③点击修改布尔值,显示抽屉
<el-button type="primary" @click="onAddArticle">发布文章</el-button>const visibleDrawer = ref(false)
const onAddArticle = () => {visibleDrawer.value = true
}
(2)封装抽屉组件ArticleEdit
添加 和 编辑,可以共用一个抽屉,所以可以将抽屉封装成一个组件。
①封装组件src/views/article/components/ArticleEdit.vue
<script setup>
import { ref } from 'vue'
// 控制抽屉的显示隐藏
const visibleDrawer = ref(false)// 组件对外暴露一个方法open,基于open传来的参数,区分添加还是编辑
// open({}) => 表单无需渲染,说明是添加
// open({id, ..., ...}) => 表单需要渲染(数据回显),说明是编辑
// open调用后,可以打开弹窗
const open = (row) => {visibleDrawer.value = true // 显示抽屉console.log(row)
}// 向外暴露方法
defineExpose({open
})
</script><template><!-- 抽屉区 --><el-drawer v-model="visibleDrawer" title="大标题" direction="rtl" size="50%"><span>Hi, there!</span></el-drawer>
</template>
②通过ref进行绑定
const articleEditRef = ref()<!-- 抽屉区域 -->
<article-edit ref="articleEditRef"></article-edit>
③点击调用方法显示抽屉
// 添加逻辑
const onAddArticle = () => {articleEditRef.value.open({})
}// 编辑
const onEditArticle = (row) => {// console.log(row)articleEditRef.value.open(row)
}
(3)完善抽屉表单结构
①准备数据
// 默认数据
const defaultForm = {title: '', // 标题cate_id: '', // 分类idcover_img: '', // 封面图片 file对象content: '', // string内容state: '' // 状态
}// 准备数据
const formModel = ref({...defaultForm
})// 组件对外暴露一个方法open,基于open传来的参数,区分添加还是编辑
// open({}) => 表单无需渲染,说明是添加
// open({id, ..., ...}) => 表单需要渲染(数据回显),说明是编辑
// open调用后,可以打开弹窗
const open = (row) => {visibleDrawer.value = true // 显示抽屉if (row.id) {// 需要基于row.id发送请求,获取编辑对应的详情数据,进行回显console.log('编辑回显')} else {formModel.value = { ...defaultForm } // 基于默认的数据,重置form数据console.log('添加')}console.log(row)
}
②准备form表单结构
import ChannelSelect from './ChannelSelect.vue'<template><el-drawerv-model="visibleDrawer":title="formModel.id ? '编辑文章' : '添加文章'"direction="rtl"size="50%"><!-- 发表文章表单 --><el-form :model="formModel" ref="formRef" label-width="100px"><el-form-item label="文章标题" prop="title"><el-input v-model="formModel.title" placeholder="请输入标题"></el-input></el-form-item><el-form-item label="文章分类" prop="cate_id"><channel-selectv-model="formModel.cate_id"width="100%"></channel-select></el-form-item><el-form-item label="文章封面" prop="cover_img"> 文件上传 </el-form-item><el-form-item label="文章内容" prop="content"><div class="editor">富文本编辑器</div></el-form-item><el-form-item><el-button type="primary">发布</el-button><el-button type="info">草稿</el-button></el-form-item></el-form></el-drawer>
</template>
③扩展下拉菜单width props
src/views/article/components/ChannelSelect.vue
<script setup>
import { artGetChannelsService } from '@/api/article.js'
import { ref } from 'vue'defineProps({modelValue: {type: [Number, String]},width: {type: String}
})
// ......
</script><template><el-select:modelValue="modelValue"@update:modelValue="emit('update:modelValue', $event)"placeholder="请选择"size="large":style="{ width }"><!-- ...... --></el-select>
</template>
(4)上传文件9lement-plus - 文件预览]
Upload 上传 | Element Plus
src/views/article/components/ArticleEdit.vue
<script setup>
import { ref } from 'vue'
import ChannelSelect from './ChannelSelect.vue'
import { Plus } from '@element-plus/icons-vue'// 控制抽屉的显示隐藏
const visibleDrawer = ref(false)// 默认数据
const defaultForm = {title: '', // 标题cate_id: '', // 分类idcover_img: '', // 封面图片 file对象content: '', // string内容state: '' // 状态
}// 准备数据
const formModel = ref({...defaultForm
})// 图片上传相关逻辑
const imgUrl = ref('')
const onSelectFile = (uploadFile) => {// console.log(uploadFile)imgUrl.value = URL.createObjectURL(uploadFile.raw) // 预览图片formModel.value.cover_img = uploadFile.raw
}// 组件对外暴露一个方法open,基于open传来的参数,区分添加还是编辑
// open({}) => 表单无需渲染,说明是添加
// open({id, ..., ...}) => 表单需要渲染(数据回显),说明是编辑
// open调用后,可以打开弹窗
const open = (row) => {visibleDrawer.value = true // 显示抽屉if (row.id) {// 需要基于row.id发送请求,获取编辑对应的详情数据,进行回显console.log('编辑回显')} else {formModel.value = { ...defaultForm } // 基于默认的数据,重置form数据console.log('添加')}// console.log(row)
}// 向外暴露方法
defineExpose({open
})
</script><template><el-drawerv-model="visibleDrawer":title="formModel.id ? '编辑文章' : '添加文章'"direction="rtl"size="50%"><!-- 发表文章表单 --><el-form :model="formModel" ref="formRef" label-width="100px"><el-form-item label="文章标题" prop="title"><el-input v-model="formModel.title" placeholder="请输入标题"></el-input></el-form-item><el-form-item label="文章分类" prop="cate_id"><channel-selectv-model="formModel.cate_id"width="100%"></channel-select></el-form-item><el-form-item label="文章封面" prop="cover_img"><!-- 此处需要关闭element-plus的自动上传,不需要配置action等参数此处只需要做前端的本地预览图片即可,无需在提交前上传图片语法:URL.createObjectURL(...)创建本地预览的地址,来预览--><el-uploadclass="avatar-uploader":show-file-list="false":auto-upload="false":on-change="onSelectFile"><img v-if="imgUrl" :src="imgUrl" class="avatar" /><el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon></el-upload></el-form-item><el-form-item label="文章内容" prop="content"><div class="editor">富文本编辑器</div></el-form-item><el-form-item><el-button type="primary">发布</el-button><el-button type="info">草稿</el-button></el-form-item></el-form></el-drawer>
</template><style lang="scss" scoped>
.avatar-uploader {:deep() {.avatar {width: 178px;height: 178px;display: block;}.el-upload {border: 1px dashed var(--el-border-color);border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;transition: var(--el-transition-duration-fast);}.el-upload:hover {border-color: var(--el-color-primary);}.el-icon.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 178px;height: 178px;text-align: center;}}
}
</style>
3. 编辑文章(共用抽屉)
(1)富文本编辑器[vue-quill]
官网地址:Introduction | VueQuill
①安装
pnpm add @vueup/vue-quill@latest
②注册成局部组件
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
③页面中使用绑定
<div class="editor"><quill-editortheme="snow"v-model:content="formModel.content"contentType="html"></quill-editor>
</div>
④样式美化
.editor {width: 100%;:deep(.ql-editor) {min-height: 200px;}
}
(2)添加文章功能
①封装添加接口 - src/api/article.js
// 文章:添加文章
// 注意:data需要是一个formData格式的对象
export const artPublishService = (data) => request.post('/my/article/add', data)
②注册点击事件调用
ArticleEdit.vue
<el-form-item><el-button @click="onPublish('已发布')" type="primary">发布</el-button><el-button @click="onPublish('草稿')" type="info">草稿</el-button>
</el-form-item>
// 发布文章
const emit = defineEmits(['success'])
const onPublish = async (state) => {// 将已发布还是草稿状态,存入 stateformModel.value.state = state// 转换 formData 数据const fd = new FormData()for (let key in formModel.value) {fd.append(key, formModel.value[key])}if (formModel.value.id) {console.log('编辑操作')} else {// 添加请求await artPublishService(fd)ElMessage.success('添加成功')visibleDrawer.value = falseemit('success', 'add')}
}
③父组件监听事件,重新渲染
ArticleManage.vue
<!-- 抽屉区域 -->
<article-edit ref="articleEditRef" @success="onSuccess"></article-edit>
// 添加或者编辑 成功的回调
const onSuccess = (type) => {if (type === 'add') {// 如果是添加,需跳转渲染最后一页,编辑直接渲染当前页const lastPage = Math.ceil((total.value + 1) / params.value.pagesize)// 更新成最大页码数,再渲染params.value.pagenum = lastPage}getArticleList()
}
④添加完成后的内容重置 - ArticleEdit.vue
Methods | VueQuill (vueup.github.io)
const editorRef = ref()
const open = (row) => {visibleDrawer.value = true // 显示抽屉if (row.id) {// 需要基于row.id发送请求,获取编辑对应的详情数据,进行回显// console.log('编辑回显')} else {formModel.value = { ...defaultForm } // 基于默认的数据,重置form数据// 这里重置了表单的数据,但是图片上传img地址、富文本编辑器内容,需要手动重置imgUrl.value = ''editorRef.value.setHTML('')}
}
(3)编辑文章回显
如果是编辑操作,一打开抽屉,就需要发送请求,获取数据进行回显
①封装接口,根据id获取数据详情数据
src/api/article.js
// 根据id获取详情数据
export const artGetDetailService = (id) =>request.get('my/article/info', { params: { id } })
②页面中调用渲染 - ArticleEdit.vue
import { baseURL } from '@/utils/request.js'const open = async (row) => {visibleDrawer.value = true // 显示抽屉if (row.id) {console.log('编辑回显')// 需要基于row.id发送请求,获取编辑对应的详情数据,进行回显const res = await artGetDetailService(row.id)// console.log(res)formModel.value = res.data.data// 图片需要单独处理回显imgUrl.value = baseURL + formModel.value.cover_img// 提交给后台,需要的是file格式,将网络图片,转成file格式// 将网络图片地址 转成file对象,存储起来,将来便于提交formModel.value.cover_img = await imageUrlToFileObject(imgUrl.value,formModel.value.cover_img)} else {// 添加功能formModel.value = { ...defaultForm } // 基于默认的数据,重置form数据// 这里重置了表单的数据,但是图片上传img地址、富文本编辑器内容,需要手动重置imgUrl.value = ''editorRef.value.setHTML('')}
}// 将网络图片地址转换为File对象
async function imageUrlToFileObject(url, fileName) {try {// 第一步:使用axios获取网络图片数据const response = await axios.get(url, { responseType: 'arraybuffer' })const imageData = response.data// 第二步:将图片数据转换为Blob对象const blob = new Blob([imageData], {type: response.headers['content-type']})// 第三步:创建一个新的File对象const file = new File([blob], fileName, { type: blob.type })return file} catch (error) {console.error('将图片转换为File对象时发生错误:', error)throw error}
}
(4)编辑文章功能
①封装编辑接口
src/api/article.js
// 文章:编辑文章
export const artEditService = (data) => request.put('/my/article/info', data)
②提交时调用 - ArticleEdit.vue
// 提交
const onPublish = async (state) => {// ......// 发请求if (formModel.value.id) {// 编辑操作// console.log('编辑操作')await artEditService(fd)ElMessage.success('修改成功')visibleDrawer.value = falseemit('success', 'edit')} else {// 添加操作// ......}
}
4. 删除文章
①封装删除接口 - article.js
// 文章:删除文章
export const artDelService = (id) => {request.delete('/my/article/info', { params: { id } })
}
②页面中添加确认框调用 - ArticleManage.vue
import { artGetListService, artDelService } from '@/api/article.js'
// 删除
const onDeleteArticle = async (row) => {await ElMessageBox.confirm('你确认要删除该文章信息吗?', '温馨提示', {type: 'warning',confirmButtonText: '确认',cancelButtonText: '取消'})await artDelService(row.id)ElMessage({ type: 'success', message: '删除成功' })getArticleList()
}
十六、ChatGPT & Copilot
讲解内容:
1. AI的认知 & 两个工具
2. ChatGPT的基本使用(Prompt优化)
3. Copilot的基本使用(代码实战,高效编码)
4. 个人中心项目实战
- 基本资料
- 更换头像
- 重置密码
1. AI的认知 & 两个工具
(1)认知同步:
1. AI早已不是新事物(接受)
语音识别、人脸识别、无人驾驶、智能机器人
2. AI本质是智能工具(认识)
人工智能辅助,可以提升效率,但不具备思想意识,无法从零到一取代人类工作
3. AI一定会淘汰掉一部分人
但一定会衍生出新的职业方向
(2)两个工具: ChatGPT & Copilot
ChatGPT:GitHub - LiLittleCat/awesome-free-chatgpt: 🆓免费的 ChatGPT 镜像网站列表,持续更新。List of free ChatGPT mirror sites, continuously updated.
Githunb Copilot智能生成代码:
Sign in to GitHub · GitHub
2. ChatGPT的基本使用(Prompt优化)
AI 互动的过程中,容易出现的问题:
-
AI未能理解问题的核心要点
-
AI的回答过于宽泛 或 过于具体
-
AI提供了错误的信息或观点
-
AI未能提供有价值的建议或解决方案
在识别了问题所在之后,我们可以尝试以下策略来优化我们的Prompt:
-
明确提问:
确保问题表述清晰明确,关键字的准确度,决定了AI 对于需求的理解。
-
细化需求:
将问题拆分成多个小问题,可以帮助AI更具针对性地回答,也利于即时纠错。
-
添加背景信息:
提供有关问题背景的详细信息,也可以给 AI 预设一个角色,将有助于AI生成更具深度和价值的回答。
-
适当引导:
比如:“例如”、“请注意”、“请使用”等,来告诉模型你期望它做什么 或者 不做什么
-
限制范围:
通过限定回答的范围和长度,可以引导AI生成更精炼的回答
案例 - 前端简历
Prompt 优化前:
Prompt1:
前端简历
Prompt 优化后:
Prompt1:
背景:你是一名【具有三年开发经验】的前端开发工程师,这三年期间,前两年,你做的【金融】相关四个项目,最后一年做的是【医疗】相关领域的两个项目,且有一定的管理 10人+ 团队的经验。主要的技术栈:【Vue】 和 【小程序】。由于你是计算机软件工程专业,所以你具备一些Java后台、Mysql数据库的知识,也掌握一些基础的算法。
问题:你会如何编写你的简历个人技能介绍
要求:8条技能介绍,请注意:你不会 angular。
Prompt2:
基于上文情境,你会如何编写你的项目经验介绍
Prompt3:
你刚才说的方向完全没有问题,但是我想看到更多的项目技术亮点,项目业务解决方案。
请注意:每个项目3个技术亮点,3个业务解决方案。
3. Copilot的基本使用(代码实战,高效编码)
安装步骤
- 登录github,试用Copilot
- 打开vscode,搜索安装插件Copilot
使用说明
- 删除键:不接受
- Tab键:接受
- Crtl + enter:查看更多方案
4. 个人中心项目实战
(1)基本资料
①封装接口,更新个人信息 - src/api/iser.js
// 更新个人信息
export const userUpdateInfoService = ({ id, nickname, email }) => {request.put('/my/userinfo', { id, nickname, email })
}
②静态结构 + 校验处理,页面中校验后,封装调用 - src/views/user/UserProfile.vue
<script setup>
import PageContainer from '@/components/PageContainer.vue'
import { ref } from 'vue'
import { useUserStore } from '@/stores'
import { userUpdateInfoService } from '@/api/user'const formRef = ref()// 是在使用仓库中数据的初始值 (无需响应式) 解构无问题
const {user: { email, id, nickname, username },getUser
} = useUserStore()const form = ref({id,username,nickname,email
})const rules = ref({nickname: [{ required: true, message: '请输入用户昵称', trigger: 'blur' },{pattern: /^\S{2,10}/,message: '昵称长度在2-10个非空字符',trigger: 'blur'}],email: [{ required: true, message: '请输入用户邮箱', trigger: 'blur' },{type: 'email',message: '请输入正确的邮箱格式',trigger: ['blur', 'change']}]
})const submitForm = async () => {// 等待校验结果await formRef.value.validate()// 提交修改await userUpdateInfoService(form.value)// 通知 user 模块,进行数据的更新getUser()// 提示用户ElMessage.success('修改成功')
}
</script>
<template><page-container title="基本资料"><!-- 表单部分 --><el-form ref="formRef" :model="form" :rules="rules" label-width="100px"><el-form-item label="登录名称"><el-input v-model="form.username" disabled></el-input></el-form-item><el-form-item label="用户昵称" prop="nickname"><el-input v-model="form.nickname"></el-input></el-form-item><el-form-item label="用户邮箱" prop="email"><el-input v-model="form.email"></el-input></el-form-item><el-form-item><el-button type="primary" @click="submitForm">提交修改</el-button></el-form-item></el-form></page-container>
</template>
(2)更换头像
①封装接口 - src/api/user.js
// 更新头像
export const userUpdateAvatarService = (avatar) => {request.patch('/my/update/avatar', { avatar })
}
②静态结构 ,封装调用 - src/views/user/UserAvatar.vue
<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUpdateAvatarService } from '@/api/user'
const userStore = useUserStore()
const imgUrl = ref(userStore.user.user_pic)
const uploadRef = ref()
const onSelectFile = (uploadFile) => {// 基于 FileReader 读取图片做预览const reader = new FileReader()reader.readAsDataURL(uploadFile.raw)reader.onload = () => {imgUrl.value = reader.result}
}const onUpdateAvatar = async () => {// 发送请求更新头像await userUpdateAvatarService(imgUrl.value)// userStore 重新渲染await userStore.getUser()// 提示用户ElMessage.success('头像更新成功')
}
</script><template><page-container title="更换头像"><el-uploadref="uploadRef":auto-upload="false"class="avatar-uploader":show-file-list="false":on-change="onSelectFile"><img v-if="imgUrl" :src="imgUrl" class="avatar" /><el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon></el-upload><br /><el-button@click="uploadRef.$el.querySelector('input').click()"type="primary":icon="Plus"size="large">选择图片</el-button><el-button@click="onUpdateAvatar"type="success":icon="Upload"size="large">上传头像</el-button></page-container>
</template><style lang="scss" scoped>
.avatar-uploader {:deep() {.avatar {width: 278px;height: 278px;display: block;}.el-upload {border: 1px dashed var(--el-border-color);border-radius: 6px;cursor: pointer;position: relative;overflow: hidden;transition: var(--el-transition-duration-fast);}.el-upload:hover {border-color: var(--el-color-primary);}.el-icon.avatar-uploader-icon {font-size: 28px;color: #8c939d;width: 278px;height: 278px;text-align: center;}}
}
</style>
(3)重置密码
①封装接口 - src/api/user.js
// 重置密码
export const userUpdatePasswordService = ({ old_pwd, new_pwd, re_pwd }) => {request.patch('/my/updatepwd', { old_pwd, new_pwd, re_pwd })
}
②静态结构 ,封装调用 - src/views/user/UserAvatar.vue
<script setup>
import { ref } from 'vue'
import { userUpdatePasswordService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'const formRef = ref()
const pwdForm = ref({old_pwd: '',new_pwd: '',re_pwd: ''
})const checkDifferent = (rule, value, callback) => {// 校验新密码和原密码不能一样if (value === pwdForm.value.old_pwd) {callback(new Error('新密码不能与原密码一样'))} else {callback()}
}
const checkSameAsNewPwd = (rule, value, callback) => {// 校验确认密码必须和新密码一样if (value !== pwdForm.value.new_pwd) {callback(new Error('确认密码必须和新密码一样'))} else {callback()}
}
const rules = ref({old_pwd: [{ required: true, message: '请输入原密码', trigger: 'blur' },{ min: 6, max: 15, message: '原密码长度在6-15位之间', trigger: 'blur' }],new_pwd: [{ required: true, message: '请输入新密码', trigger: 'blur' },{ min: 6, max: 15, message: '新密码长度在6-15位之间', trigger: 'blur' },{ validator: checkDifferent, trigger: 'blur' }],re_pwd: [{ required: true, message: '请再次输入新密码', trigger: 'blur' },{ min: 6, max: 15, message: '确认密码长度在6-15位之间', trigger: 'blur' },{ validator: checkSameAsNewPwd, trigger: 'blur' }]
})const userStore = useUserStore()
const router = useRouter()const submitForm = async () => {await formRef.value.validate()await userUpdatePasswordService(pwdForm.value)ElMessage.success('密码修改成功')// 密码修改成功后,退出重新登录// 清空本地存储的 token 和 个人信息userStore.setToken('')userStore.setUser({})// 拦截登录router.push('/login')
}const resetForm = () => {formRef.value.resetFields()
}
</script><template><page-container title="修改密码"><el-row><el-col :span="12"><el-formref="formRef":model="pwdForm":rules="rules"label-width="100px"><el-form-item label="原密码" prop="old_pwd"><el-input v-model="pwdForm.old_pwd" show-password></el-input></el-form-item><el-form-item label="新密码" prop="new_pwd"><el-input v-model="pwdForm.new_pwd" show-password></el-input></el-form-item><el-form-item label="确认密码" prop="re_pwd"><el-input v-model="pwdForm.re_pwd" show-password></el-input></el-form-item><el-form-item><el-button type="primary" @click="submitForm">修改密码</el-button><el-button @click="resetForm">重置</el-button></el-form-item></el-form></el-col></el-row></page-container>
</template>
至此,完结撒花~