当前位置:   article > 正文

【SpringBoot3+Vue3】五【完】【实战篇】-前端(配合后端)

springboot3+vue3

目录

一、环境准备

1、创建Vue工程

2、安装依赖 

2.1 安装项目所需要的vue依赖 

2.2 安装element-plus依赖

2.2.1 安装

2.2.2 项目导入element-plus

2.3 安装axios依赖

2.4 安装sass依赖

3、目录调整

3.1 删除部分默认目录下文件

3.1.1 src/components下自动生成的内容(删除文件夹下全部内容)

3.1.2 src/assets 下自动生成的内容(删除文件夹下全部内容) 

3.2 api、utils、views目录处理

3.2.1 src下新建目录api、utils、views

 3.2.2 utils下新增request.js文件

3.3 将资料中的静态资源拷贝到assets目录下

3.4 修改app.vue生成的内容

4、启动项目验证

二、注册功能

1、页面搭建 

1.1 views下新建Login.vue

1.2 App.vue导入Login.vue

1.3 查看结果

2、为注册页面绑定数据与事件

2.1 定义数据模型Login.vue

 2.2 注册页面Login.vue表单校验

2.3 验证

3、注册页面后台接口调用 

3.1 启动后端服务

3.2 api目录下新建user.js文件

3.3 Login.vue页面完成调用

4、跨域问题解决

4.1 request.js

4.2 vite.config.js

5、测试验证

三、登录功能

1、登录Login.vue绑定数据 

2、 登录Login.vue数据校验

3、登录页面后端接口调用

3.1 user.js提供登录调用接口

3.2 Login.vue调用后端接口

4、测试验证

5、优化登录表单与注册表单数据显示问题(Login.vue)

四、优化axios响应拦截器与alert

1、axios响应拦截器

2.1 request.js 

2.2 优化Login.vue

2、使用element-plus优化alert

2.1 request.js引用ElMessage 组件处理

2.2  Login.vue引用ElMessage 组件处理

五、主页面布局 

1、Layout页面

1.1 views下新增Layout.vue

 1.2 App.vue导入Layout.vue

2、路由

 2.1 安装vue-router

2.2 创建路由器index.js

2.3 在main.js使用vue-router

2.4 App.vue中声明router-view标签

2.5  Login.vue优化登录成功跳转

2.6 测试验证

3、子路由

3.1 views下创建vue文件 

3.1.1 ArticleCategory.vue

3.1.2 ArticleManage.vue

3.1.3 UserAvatar.vue

3.1.4 UserInfo.vue

3.1.5 UserResetPassword.vue

3.2 index.js

3.3 Layout.vue声明router-view标签

3.4 测试验证

六、文章分类 

1、列表查询

1.1 article.js

1.2 ArticleCategory.vue

2、Pinia状态管理库

2.1 安装pinia

2.2 main.js导入pinia

2.3 定义store

2.4 使用Store

2.5 测试验证

 3、 使用axios请求拦截器解决token繁琐问题

​编辑 3.1 request.js添加请求拦截器

3.2 article.js移除之前添加的请求头

4、pinia-persistedstate-plugin持久化插件

4.1 安装

4.2 pinia中使用persist插件

4.3 在创建定义状态是配置持久化

5、未登录统一处理

6、添加文章分类

6.1  ArticleCategory.vue

6.2 在article.js中提供添加分类的函数

6.3 测试验证

7、修改文章分类 

7.1 修改分类弹窗页面

7.1.1 弹窗标题显示  ArticleCategory.vue

7.1.2 在弹窗上绑定标题 ArticleCategory.vue

7.1.3 为添加分类按钮绑定事件 ArticleCategory.vue

7.1.4 为修改分类按钮绑定事件 ArticleCategory.vue

7.2 修改数据回显 ArticleCategory.vue

7.3 修改文章分类接口调用

7.3.1 article.js中提供修改分类的函数

7.3.2 修改确定按钮的绑定事件 ArticleCategory.vue

7.3.3 调用接口完成修改的函数  ArticleCategory.vue

7.3.4 优化添加时数据回显

8、删除文章分类

 8.1 删除接口

8.2 删除确认框

 8.3 为删除按钮绑定事件

8.4 调用删除接口

8.5 测试验证

七、文章列表 

1、 文章列表查询

 1.1 文章列表页面组件ArticleManage.vue

1.2 解决分页控件英文显示问题main.js

1.3 文章分类数据回显ArticleMange.vue  

1.4 文章列表接口调用

1.4.1 article.js中提供获取文章列表数据的函数

1.4.2 ArticleManage.vue中,调用接口获取数据

1.4.3 当分页条的当前页和每页条数发生变化,重新发送请求获取数据

2 、搜索和重置

3、添加文章

3.1 添加文章抽屉组件

3.2 为添加文章按钮添加单击事件,展示抽屉

3.3 富文本编辑器

3.3.1 安装:

3.3.2 导入组件和样式:

3.3.3 页面使用quill组件:​

3.3.4 样式美化:

3.4 文章封面图片上传

3.5 添加文章接口调用

3.5.1 article.js中提供添加文章函数

3.5.2 为已发布和草稿按钮绑定事件

3.5.3 ArticleManage.vue中提供addArticle函数完成添加文章接口的调用

4、编辑文章

4.1 修改文章抽屉页面

4.1.1 抽屉标题显示 定义标题

4.1.2 在抽屉上绑定标题

4.1.3 为添加文章按钮绑定事件

4.1.4 为修改文章按钮绑定事件

4.2 数据回显

4.2.1 通过插槽的方式得到被点击按钮所在行的数据

4.2.2 回显函数

4.3 修改文章接口调用

4.3.1 article.js中提供修改文章的函数

4.3.2 修改发布与草稿按钮的绑定事件

4.3.3 调用接口完成修改的函数

5、删除文章

5.1 接口调用

5.2 为删除按钮绑定事件

5.3 添加删除弹窗,当用户点击确认后,调用接口删除分类

八、顶部导航栏信息展示

1、 user.js中提供获取个人信息的函数

2、 src/stores/userInfo.js中,定义个人中心状态

3、 Layout.vue中获取个人信息,并存储到pinia中

4、Layout.vue的顶部导航栏中,展示昵称和头像

九 、页面右上角下拉菜单el-dropdown中功能实现

1、路由实现:

2、 退出登录实现:

十、基本资料修改

1、 基本资料页面组件UserInfo.vue

2、 表单数据回显

3、 接口调用

十一、修改头像

1、 修改头像页面组件UserAvatar.vue

2、 头像回显

3、 头像上传

4、 上传头像接口调用

十二、 重置密码

1、user.js 重置密码

 2、UserResetPassword.vue


前言:本项目的终结篇,是一名vue3完成本次课程的前端页面。

一、环境准备

1、创建Vue工程

  1. npm init vue@latest
  2. # 项目名称spring3vue3project

2、安装依赖 

进入到创建项目目录

2.1 安装项目所需要的vue依赖 

  1. # 项目所需要的vue依赖
  2. npm install

2.2 安装element-plus依赖

2.2.1 安装
  1. # 安装element-plus依赖
  2. npm install element-plus --save

2.2.2 项目导入element-plus

打开项目 

code .

修改src/main.js 

  1. import './assets/main.scss'
  2. import { createApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. import App from './App.vue'
  6. const app = createApp(App)
  7. app.use(ElementPlus)
  8. app.mount('#app')

2.3 安装axios依赖

npm install axios

2.4 安装sass依赖

  1. # 安装sass依赖 好像是关于css的
  2. npm install sass -D

3、目录调整

直接进到项目文件夹下操作

3.1 删除部分默认目录下文件

3.1.1 src/components下自动生成的内容(删除文件夹下全部内容)

3.1.2 src/assets 下自动生成的内容(删除文件夹下全部内容) 

3.2 api、utils、views目录处理

3.2.1 src下新建目录api、utils、views

 3.2.2 utils下新增request.js文件
  1. // 定制请求实例
  2. //导入axios
  3. import axios from 'axios';
  4. //定义一个变量,记录公共的前缀baseURL
  5. const baseURL = 'http://localhost:8080'
  6. const instance = axios.create({baseURL})
  7. // 添加响应拦截器
  8. instance.interceptors.response.use(
  9. result=>{
  10. return result.data;
  11. },
  12. err=>{
  13. alert('服务异常')
  14. return Promise.reject(err);//异步的状态转化成失败的状态
  15. }
  16. )
  17. export default instance;

3.3 将资料中的静态资源拷贝到assets目录下

如需,关注,发私信

3.4 修改app.vue生成的内容

删除app.vue中自动生成的内容

  1. <script setup>
  2. </script>
  3. <template>
  4. 春天的菠菜
  5. </template>
  6. <style scoped>
  7. </style>

4、启动项目验证

npm run dev

二、注册功能

 

1、页面搭建 

1.1 views下新建Login.vue

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //控制注册与登录表单的显示, 默认显示注册
  5. const isRegister = ref(false)
  6. </script>
  7. <template>
  8. <el-row class="login-page">
  9. <el-col :span="12" class="bg"></el-col>
  10. <el-col :span="6" :offset="3" class="form">
  11. <!-- 注册表单 -->
  12. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister">
  13. <el-form-item>
  14. <h1>注册</h1>
  15. </el-form-item>
  16. <el-form-item>
  17. <el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
  18. </el-form-item>
  19. <el-form-item>
  20. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
  21. </el-form-item>
  22. <el-form-item>
  23. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码"></el-input>
  24. </el-form-item>
  25. <!-- 注册按钮 -->
  26. <el-form-item>
  27. <el-button class="button" type="primary" auto-insert-space>
  28. 注册
  29. </el-button>
  30. </el-form-item>
  31. <el-form-item class="flex">
  32. <el-link type="info" :underline="false" @click="isRegister = false">
  33. ← 返回
  34. </el-link>
  35. </el-form-item>
  36. </el-form>
  37. <!-- 登录表单 -->
  38. <el-form ref="form" size="large" autocomplete="off" v-else>
  39. <el-form-item>
  40. <h1>登录</h1>
  41. </el-form-item>
  42. <el-form-item>
  43. <el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
  44. </el-form-item>
  45. <el-form-item>
  46. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
  47. </el-form-item>
  48. <el-form-item class="flex">
  49. <div class="flex">
  50. <el-checkbox>记住我</el-checkbox>
  51. <el-link type="primary" :underline="false">忘记密码?</el-link>
  52. </div>
  53. </el-form-item>
  54. <!-- 登录按钮 -->
  55. <el-form-item>
  56. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  57. </el-form-item>
  58. <el-form-item class="flex">
  59. <el-link type="info" :underline="false" @click="isRegister = true">
  60. 注册 →
  61. </el-link>
  62. </el-form-item>
  63. </el-form>
  64. </el-col>
  65. </el-row>
  66. </template>
  67. <style lang="scss" scoped>
  68. /* 样式 */
  69. .login-page {
  70. height: 100vh;
  71. background-color: #fff;
  72. .bg {
  73. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  74. url('@/assets/login_bg.jpg') no-repeat center / cover;
  75. border-radius: 0 20px 20px 0;
  76. }
  77. .form {
  78. display: flex;
  79. flex-direction: column;
  80. justify-content: center;
  81. user-select: none;
  82. .title {
  83. margin: 0 auto;
  84. }
  85. .button {
  86. width: 100%;
  87. }
  88. .flex {
  89. width: 100%;
  90. display: flex;
  91. justify-content: space-between;
  92. }
  93. }
  94. }
  95. </style>

1.2 App.vue导入Login.vue

  1. <script setup>
  2. import LoginVue from '@/views/Login.vue'
  3. </script>
  4. <template>
  5. <LoginVue/>
  6. </template>
  7. <style scoped>
  8. </style>

1.3 查看结果

2、为注册页面绑定数据与事件

2.1 定义数据模型Login.vue

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //控制注册与登录表单的显示, 默认显示注册
  5. const isRegister = ref(false)
  6. //定义数据模型
  7. const registerData = ref({
  8. username:'',
  9. password:'',
  10. rePassword:''
  11. })
  12. </script>
  13. <template>
  14. <el-row class="login-page">
  15. <el-col :span="12" class="bg"></el-col>
  16. <el-col :span="6" :offset="3" class="form">
  17. <!-- 注册表单 -->
  18. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData">
  19. <el-form-item>
  20. <h1>注册</h1>
  21. </el-form-item>
  22. <el-form-item>
  23. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
  24. </el-form-item>
  25. <el-form-item>
  26. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
  27. </el-form-item>
  28. <el-form-item>
  29. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input>
  30. </el-form-item>
  31. <!-- 注册按钮 -->
  32. <el-form-item>
  33. <el-button class="button" type="primary" auto-insert-space>
  34. 注册
  35. </el-button>
  36. </el-form-item>
  37. <el-form-item class="flex">
  38. <el-link type="info" :underline="false" @click="isRegister = false">
  39. ← 返回
  40. </el-link>
  41. </el-form-item>
  42. </el-form>
  43. <!-- 登录表单 -->
  44. <el-form ref="form" size="large" autocomplete="off" v-else>
  45. <el-form-item>
  46. <h1>登录</h1>
  47. </el-form-item>
  48. <el-form-item>
  49. <el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
  50. </el-form-item>
  51. <el-form-item>
  52. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
  53. </el-form-item>
  54. <el-form-item class="flex">
  55. <div class="flex">
  56. <el-checkbox>记住我</el-checkbox>
  57. <el-link type="primary" :underline="false">忘记密码?</el-link>
  58. </div>
  59. </el-form-item>
  60. <!-- 登录按钮 -->
  61. <el-form-item>
  62. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  63. </el-form-item>
  64. <el-form-item class="flex">
  65. <el-link type="info" :underline="false" @click="isRegister = true">
  66. 注册 →
  67. </el-link>
  68. </el-form-item>
  69. </el-form>
  70. </el-col>
  71. </el-row>
  72. </template>
  73. <style lang="scss" scoped>
  74. /* 样式 */
  75. .login-page {
  76. height: 100vh;
  77. background-color: #fff;
  78. .bg {
  79. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  80. url('@/assets/login_bg.jpg') no-repeat center / cover;
  81. border-radius: 0 20px 20px 0;
  82. }
  83. .form {
  84. display: flex;
  85. flex-direction: column;
  86. justify-content: center;
  87. user-select: none;
  88. .title {
  89. margin: 0 auto;
  90. }
  91. .button {
  92. width: 100%;
  93. }
  94. .flex {
  95. width: 100%;
  96. display: flex;
  97. justify-content: space-between;
  98. }
  99. }
  100. }
  101. </style>

 2.2 注册页面Login.vue表单校验

表单校验可看官网

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //控制注册与登录表单的显示, 默认显示注册
  5. const isRegister = ref(false)
  6. //2.1定义数据模型
  7. const registerData = ref({
  8. username:'',
  9. password:'',
  10. rePassword:''
  11. })
  12. //2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  13. const checkRePassword = (rule,value,callback)=>{
  14. if(value === '' ){
  15. callback(new Error('请再次确认密码!'))
  16. }else if(value !== registerData.value.password){
  17. callback(new Error('请确保两次密码输入一致性!'))
  18. }else{
  19. callback() //校验通过
  20. }
  21. }
  22. //2.2 定义表单校验规则,rePassword需要自定义校验规则
  23. const rules = {
  24. username:[
  25. {required:true,message:'请输入用户名!',trigger:'blur'},
  26. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  27. ],
  28. password:[
  29. {required:true,message:'请输入密码!',trigger:'blur'},
  30. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  31. ],
  32. rePassword:[
  33. {validator:checkRePassword,trigger:'blur'}
  34. ]
  35. }
  36. </script>
  37. <template>
  38. <el-row class="login-page">
  39. <el-col :span="12" class="bg"></el-col>
  40. <el-col :span="6" :offset="3" class="form">
  41. <!-- 注册表单 -->
  42. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 2.1 :model="registerData"表单声明属性 --> <!-- 2.2 :rules="rules"绑定校验 -->
  43. <el-form-item>
  44. <h1>注册</h1>
  45. </el-form-item>
  46. <el-form-item prop="username"> <!-- 2.2 prop="username"绑定校验 -->
  47. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!-- 2.1 v-model="registerData.username"绑定属性 -->
  48. </el-form-item>
  49. <el-form-item prop="password"> <!-- 2.2 prop="password"绑定校验 -->
  50. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 2.1 v-model="registerData.password"绑定属性 -->
  51. </el-form-item>
  52. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  53. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 2.1 v-model="registerData.rePassword"绑定属性 -->
  54. </el-form-item>
  55. <!-- 注册按钮 -->
  56. <el-form-item>
  57. <el-button class="button" type="primary" auto-insert-space>
  58. 注册
  59. </el-button>
  60. </el-form-item>
  61. <el-form-item class="flex">
  62. <el-link type="info" :underline="false" @click="isRegister = false">
  63. ← 返回
  64. </el-link>
  65. </el-form-item>
  66. </el-form>
  67. <!-- 登录表单 -->
  68. <el-form ref="form" size="large" autocomplete="off" v-else>
  69. <el-form-item>
  70. <h1>登录</h1>
  71. </el-form-item>
  72. <el-form-item>
  73. <el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
  74. </el-form-item>
  75. <el-form-item>
  76. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
  77. </el-form-item>
  78. <el-form-item class="flex">
  79. <div class="flex">
  80. <el-checkbox>记住我</el-checkbox>
  81. <el-link type="primary" :underline="false">忘记密码?</el-link>
  82. </div>
  83. </el-form-item>
  84. <!-- 登录按钮 -->
  85. <el-form-item>
  86. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  87. </el-form-item>
  88. <el-form-item class="flex">
  89. <el-link type="info" :underline="false" @click="isRegister = true">
  90. 注册 →
  91. </el-link>
  92. </el-form-item>
  93. </el-form>
  94. </el-col>
  95. </el-row>
  96. </template>
  97. <style lang="scss" scoped>
  98. /* 样式 */
  99. .login-page {
  100. height: 100vh;
  101. background-color: #fff;
  102. .bg {
  103. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  104. url('@/assets/login_bg.jpg') no-repeat center / cover;
  105. border-radius: 0 20px 20px 0;
  106. }
  107. .form {
  108. display: flex;
  109. flex-direction: column;
  110. justify-content: center;
  111. user-select: none;
  112. .title {
  113. margin: 0 auto;
  114. }
  115. .button {
  116. width: 100%;
  117. }
  118. .flex {
  119. width: 100%;
  120. display: flex;
  121. justify-content: space-between;
  122. }
  123. }
  124. }
  125. </style>

2.3 验证

3、注册页面后台接口调用 

3.1 启动后端服务

启动前面章节后端服务以及redis 

3.2 api目录下新建user.js文件

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }

3.3 Login.vue页面完成调用

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. // 3.3 导入注册的接口
  5. import { userRegisterService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. //3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. if(result.code ===1){
  43. //注册成功
  44. alert(result.msg?result.msg : '注册成功')
  45. }else{
  46. // 注册失败
  47. alert('注册失败')
  48. }
  49. }
  50. </script>
  51. <template>
  52. <el-row class="login-page">
  53. <el-col :span="12" class="bg"></el-col>
  54. <el-col :span="6" :offset="3" class="form">
  55. <!-- 注册表单 -->
  56. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 2.1 :model="registerData"表单声明属性 --> <!-- 2.2 :rules="rules"绑定校验 -->
  57. <el-form-item>
  58. <h1>注册</h1>
  59. </el-form-item>
  60. <el-form-item prop="username"> <!-- 2.2 prop="username"绑定校验 -->
  61. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!-- 2.1 v-model="registerData.username"绑定属性 -->
  62. </el-form-item>
  63. <el-form-item prop="password"> <!-- 2.2 prop="password"绑定校验 -->
  64. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 2.1 v-model="registerData.password"绑定属性 -->
  65. </el-form-item>
  66. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  67. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 2.1 v-model="registerData.rePassword"绑定属性 -->
  68. </el-form-item>
  69. <!-- 注册按钮 -->
  70. <el-form-item>
  71. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 3.3 @click="register" 绑定注册单击事件 -->
  72. 注册
  73. </el-button>
  74. </el-form-item>
  75. <el-form-item class="flex">
  76. <el-link type="info" :underline="false" @click="isRegister = false">
  77. ← 返回
  78. </el-link>
  79. </el-form-item>
  80. </el-form>
  81. <!-- 登录表单 -->
  82. <el-form ref="form" size="large" autocomplete="off" v-else>
  83. <el-form-item>
  84. <h1>登录</h1>
  85. </el-form-item>
  86. <el-form-item>
  87. <el-input :prefix-icon="User" placeholder="请输入用户名"></el-input>
  88. </el-form-item>
  89. <el-form-item>
  90. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
  91. </el-form-item>
  92. <el-form-item class="flex">
  93. <div class="flex">
  94. <el-checkbox>记住我</el-checkbox>
  95. <el-link type="primary" :underline="false">忘记密码?</el-link>
  96. </div>
  97. </el-form-item>
  98. <!-- 登录按钮 -->
  99. <el-form-item>
  100. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  101. </el-form-item>
  102. <el-form-item class="flex">
  103. <el-link type="info" :underline="false" @click="isRegister = true">
  104. 注册 →
  105. </el-link>
  106. </el-form-item>
  107. </el-form>
  108. </el-col>
  109. </el-row>
  110. </template>
  111. <style lang="scss" scoped>
  112. /* 样式 */
  113. .login-page {
  114. height: 100vh;
  115. background-color: #fff;
  116. .bg {
  117. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  118. url('@/assets/login_bg.jpg') no-repeat center / cover;
  119. border-radius: 0 20px 20px 0;
  120. }
  121. .form {
  122. display: flex;
  123. flex-direction: column;
  124. justify-content: center;
  125. user-select: none;
  126. .title {
  127. margin: 0 auto;
  128. }
  129. .button {
  130. width: 100%;
  131. }
  132. .flex {
  133. width: 100%;
  134. display: flex;
  135. justify-content: space-between;
  136. }
  137. }
  138. }
  139. </style>

验证,存在跨域问题

4、跨域问题解决

4.1 request.js

  1. // 定制请求实例
  2. //导入axios npm install axios
  3. import axios from 'axios';
  4. //定义一个变量,记录公共的前缀baseURL
  5. // const baseURL = 'http://localhost:8080'
  6. const baseURL = '/api' // 注释上面代码,解决跨域问题
  7. const instance = axios.create({baseURL})
  8. // 添加响应拦截器
  9. instance.interceptors.response.use(
  10. result=>{
  11. return result.data;
  12. },
  13. err=>{
  14. alert('服务异常')
  15. return Promise.reject(err);//异步的状态转化成失败的状态
  16. }
  17. )
  18. export default instance;

4.2 vite.config.js

  1. import { fileURLToPath, URL } from 'node:url'
  2. import { defineConfig } from 'vite'
  3. import vue from '@vitejs/plugin-vue'
  4. // https://vitejs.dev/config/
  5. export default defineConfig({
  6. plugins: [
  7. vue(),
  8. ],
  9. resolve: {
  10. alias: {
  11. '@': fileURLToPath(new URL('./src', import.meta.url))
  12. }
  13. }
  14. ,
  15. // server 部分都是为了解决跨域问题
  16. server:{
  17. proxy:{
  18. '/api':{//获取路径中包含了/api的请求
  19. target:'http://localhost:8080',//后台服务所在的源
  20. changeOrigin:true,//修改源
  21. rewrite:(path)=>path.replace(/^\/api/,'')///api替换为''
  22. }
  23. }
  24. }
  25. })

5、测试验证

三、登录功能

 

1、登录Login.vue绑定数据 

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口
  5. import { userRegisterService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //二 注册 2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. // 二 注册 3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. if(result.code ===1){
  43. //注册成功
  44. alert(result.msg?result.msg : '注册成功')
  45. }else{
  46. // 注册失败
  47. alert('注册失败')
  48. }
  49. }
  50. // 三 登录 1 绑定数据 复用注册表单的数据模型
  51. </script>
  52. <template>
  53. <el-row class="login-page">
  54. <el-col :span="12" class="bg"></el-col>
  55. <el-col :span="6" :offset="3" class="form">
  56. <!-- 注册表单 -->
  57. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  58. <el-form-item>
  59. <h1>注册</h1>
  60. </el-form-item>
  61. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  62. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  63. </el-form-item>
  64. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  65. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  66. </el-form-item>
  67. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  68. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  69. </el-form-item>
  70. <!-- 注册按钮 -->
  71. <el-form-item>
  72. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  73. 注册
  74. </el-button>
  75. </el-form-item>
  76. <el-form-item class="flex">
  77. <el-link type="info" :underline="false" @click="isRegister = false">
  78. ← 返回
  79. </el-link>
  80. </el-form-item>
  81. </el-form>
  82. <!-- 登录表单 -->
  83. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 -->
  84. <el-form-item>
  85. <h1>登录</h1>
  86. </el-form-item>
  87. <el-form-item>
  88. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  89. </el-form-item>
  90. <el-form-item>
  91. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  92. </el-form-item>
  93. <el-form-item class="flex">
  94. <div class="flex">
  95. <el-checkbox>记住我</el-checkbox>
  96. <el-link type="primary" :underline="false">忘记密码?</el-link>
  97. </div>
  98. </el-form-item>
  99. <!-- 登录按钮 -->
  100. <el-form-item>
  101. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  102. </el-form-item>
  103. <el-form-item class="flex">
  104. <el-link type="info" :underline="false" @click="isRegister = true">
  105. 注册 →
  106. </el-link>
  107. </el-form-item>
  108. </el-form>
  109. </el-col>
  110. </el-row>
  111. </template>
  112. <style lang="scss" scoped>
  113. /* 样式 */
  114. .login-page {
  115. height: 100vh;
  116. background-color: #fff;
  117. .bg {
  118. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  119. url('@/assets/login_bg.jpg') no-repeat center / cover;
  120. border-radius: 0 20px 20px 0;
  121. }
  122. .form {
  123. display: flex;
  124. flex-direction: column;
  125. justify-content: center;
  126. user-select: none;
  127. .title {
  128. margin: 0 auto;
  129. }
  130. .button {
  131. width: 100%;
  132. }
  133. .flex {
  134. width: 100%;
  135. display: flex;
  136. justify-content: space-between;
  137. }
  138. }
  139. }
  140. </style>

2、 登录Login.vue数据校验

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口
  5. import { userRegisterService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //二 注册 2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. // 二 注册 3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. if(result.code ===1){
  43. //注册成功
  44. alert(result.msg?result.msg : '注册成功')
  45. }else{
  46. // 注册失败
  47. alert('注册失败')
  48. }
  49. }
  50. // 三 登录 1 绑定数据 复用注册表单的数据模型
  51. // 三 登录 2 数据校验 复用注册表单的数据校验
  52. </script>
  53. <template>
  54. <el-row class="login-page">
  55. <el-col :span="12" class="bg"></el-col>
  56. <el-col :span="6" :offset="3" class="form">
  57. <!-- 注册表单 -->
  58. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  59. <el-form-item>
  60. <h1>注册</h1>
  61. </el-form-item>
  62. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  63. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  64. </el-form-item>
  65. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  66. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  67. </el-form-item>
  68. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  69. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  70. </el-form-item>
  71. <!-- 注册按钮 -->
  72. <el-form-item>
  73. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  74. 注册
  75. </el-button>
  76. </el-form-item>
  77. <el-form-item class="flex">
  78. <el-link type="info" :underline="false" @click="isRegister = false">
  79. ← 返回
  80. </el-link>
  81. </el-form-item>
  82. </el-form>
  83. <!-- 登录表单 -->
  84. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  85. <el-form-item>
  86. <h1>登录</h1>
  87. </el-form-item>
  88. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  89. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  90. </el-form-item>
  91. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  92. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  93. </el-form-item>
  94. <el-form-item class="flex">
  95. <div class="flex">
  96. <el-checkbox>记住我</el-checkbox>
  97. <el-link type="primary" :underline="false">忘记密码?</el-link>
  98. </div>
  99. </el-form-item>
  100. <!-- 登录按钮 -->
  101. <el-form-item>
  102. <el-button class="button" type="primary" auto-insert-space>登录</el-button>
  103. </el-form-item>
  104. <el-form-item class="flex">
  105. <el-link type="info" :underline="false" @click="isRegister = true">
  106. 注册 →
  107. </el-link>
  108. </el-form-item>
  109. </el-form>
  110. </el-col>
  111. </el-row>
  112. </template>
  113. <style lang="scss" scoped>
  114. /* 样式 */
  115. .login-page {
  116. height: 100vh;
  117. background-color: #fff;
  118. .bg {
  119. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  120. url('@/assets/login_bg.jpg') no-repeat center / cover;
  121. border-radius: 0 20px 20px 0;
  122. }
  123. .form {
  124. display: flex;
  125. flex-direction: column;
  126. justify-content: center;
  127. user-select: none;
  128. .title {
  129. margin: 0 auto;
  130. }
  131. .button {
  132. width: 100%;
  133. }
  134. .flex {
  135. width: 100%;
  136. display: flex;
  137. justify-content: space-between;
  138. }
  139. }
  140. }
  141. </style>

3、登录页面后端接口调用

3.1 user.js提供登录调用接口

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 二 注册函数 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }
  12. // 三 登录函数 提供调用登录接口的函数
  13. export const userLoginService = (loginData)=>{
  14. //借助于URLSearchParam完成参数传递
  15. const params = new URLSearchParams();
  16. for(let key in loginData){
  17. params.append(key,loginData[key]);
  18. }
  19. return request.post('/user/login',params);
  20. }

3.2 Login.vue调用后端接口

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //二 注册 2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. // 二 注册 3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. if(result.code ===1){
  43. //注册成功
  44. alert(result.msg?result.msg : '注册成功')
  45. }else{
  46. // 注册失败
  47. alert('注册失败')
  48. }
  49. }
  50. // 三 登录 1 绑定数据 复用注册表单的数据模型
  51. // 三 登录 2 数据校验 复用注册表单的数据校验
  52. // 三 登录 3 登录函数
  53. const login = async()=>{
  54. //调用接口完成登录
  55. let result = await userLoginService(registerData.value);
  56. if(result.code ===1){
  57. //登录成功
  58. alert(result.msg?result.msg : '登录成功')
  59. }else{
  60. // 登录失败
  61. alert('登录失败')
  62. }
  63. }
  64. </script>
  65. <template>
  66. <el-row class="login-page">
  67. <el-col :span="12" class="bg"></el-col>
  68. <el-col :span="6" :offset="3" class="form">
  69. <!-- 注册表单 -->
  70. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  71. <el-form-item>
  72. <h1>注册</h1>
  73. </el-form-item>
  74. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  75. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  76. </el-form-item>
  77. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  78. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  79. </el-form-item>
  80. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  81. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  82. </el-form-item>
  83. <!-- 注册按钮 -->
  84. <el-form-item>
  85. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  86. 注册
  87. </el-button>
  88. </el-form-item>
  89. <el-form-item class="flex">
  90. <el-link type="info" :underline="false" @click="isRegister = false">
  91. ← 返回
  92. </el-link>
  93. </el-form-item>
  94. </el-form>
  95. <!-- 登录表单 -->
  96. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  97. <el-form-item>
  98. <h1>登录</h1>
  99. </el-form-item>
  100. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  101. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  102. </el-form-item>
  103. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  104. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  105. </el-form-item>
  106. <el-form-item class="flex">
  107. <div class="flex">
  108. <el-checkbox>记住我</el-checkbox>
  109. <el-link type="primary" :underline="false">忘记密码?</el-link>
  110. </div>
  111. </el-form-item>
  112. <!-- 登录按钮 -->
  113. <el-form-item>
  114. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  115. </el-form-item>
  116. <el-form-item class="flex">
  117. <el-link type="info" :underline="false" @click="isRegister = true">
  118. 注册 →
  119. </el-link>
  120. </el-form-item>
  121. </el-form>
  122. </el-col>
  123. </el-row>
  124. </template>
  125. <style lang="scss" scoped>
  126. /* 样式 */
  127. .login-page {
  128. height: 100vh;
  129. background-color: #fff;
  130. .bg {
  131. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  132. url('@/assets/login_bg.jpg') no-repeat center / cover;
  133. border-radius: 0 20px 20px 0;
  134. }
  135. .form {
  136. display: flex;
  137. flex-direction: column;
  138. justify-content: center;
  139. user-select: none;
  140. .title {
  141. margin: 0 auto;
  142. }
  143. .button {
  144. width: 100%;
  145. }
  146. .flex {
  147. width: 100%;
  148. display: flex;
  149. justify-content: space-between;
  150. }
  151. }
  152. }
  153. </style>

4、测试验证

 

5、优化登录表单与注册表单数据显示问题(Login.vue)

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //二 注册 2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. // 二 注册 3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. if(result.code ===1){
  43. //注册成功
  44. alert(result.msg?result.msg : '注册成功')
  45. }else{
  46. // 注册失败
  47. alert('注册失败')
  48. }
  49. }
  50. // 三 登录 1 绑定数据 复用注册表单的数据模型
  51. // 三 登录 2 数据校验 复用注册表单的数据校验
  52. // 三 登录 3 登录函数
  53. const login = async()=>{
  54. //调用接口完成登录
  55. let result = await userLoginService(registerData.value);
  56. if(result.code ===1){
  57. //登录成功
  58. alert(result.msg?result.msg : '登录成功')
  59. }else{
  60. // 登录失败
  61. alert('登录失败')
  62. }
  63. }
  64. // 三 登录 4 定义函数清空数据模型数据(将数据清空)
  65. const clearRegisterDate = ()=>{
  66. registerData.value={
  67. username:'',
  68. password:'',
  69. rePassword:''
  70. }
  71. }
  72. </script>
  73. <template>
  74. <el-row class="login-page">
  75. <el-col :span="12" class="bg"></el-col>
  76. <el-col :span="6" :offset="3" class="form">
  77. <!-- 注册表单 -->
  78. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  79. <el-form-item>
  80. <h1>注册</h1>
  81. </el-form-item>
  82. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  83. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  84. </el-form-item>
  85. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  86. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  87. </el-form-item>
  88. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  89. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  90. </el-form-item>
  91. <!-- 注册按钮 -->
  92. <el-form-item>
  93. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  94. 注册
  95. </el-button>
  96. </el-form-item>
  97. <el-form-item class="flex">
  98. <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  99. ← 返回
  100. </el-link>
  101. </el-form-item>
  102. </el-form>
  103. <!-- 登录表单 -->
  104. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  105. <el-form-item>
  106. <h1>登录</h1>
  107. </el-form-item>
  108. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  109. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  110. </el-form-item>
  111. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  112. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  113. </el-form-item>
  114. <el-form-item class="flex">
  115. <div class="flex">
  116. <el-checkbox>记住我</el-checkbox>
  117. <el-link type="primary" :underline="false">忘记密码?</el-link>
  118. </div>
  119. </el-form-item>
  120. <!-- 登录按钮 -->
  121. <el-form-item>
  122. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  123. </el-form-item>
  124. <el-form-item class="flex">
  125. <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  126. 注册 →
  127. </el-link>
  128. </el-form-item>
  129. </el-form>
  130. </el-col>
  131. </el-row>
  132. </template>
  133. <style lang="scss" scoped>
  134. /* 样式 */
  135. .login-page {
  136. height: 100vh;
  137. background-color: #fff;
  138. .bg {
  139. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  140. url('@/assets/login_bg.jpg') no-repeat center / cover;
  141. border-radius: 0 20px 20px 0;
  142. }
  143. .form {
  144. display: flex;
  145. flex-direction: column;
  146. justify-content: center;
  147. user-select: none;
  148. .title {
  149. margin: 0 auto;
  150. }
  151. .button {
  152. width: 100%;
  153. }
  154. .flex {
  155. width: 100%;
  156. display: flex;
  157. justify-content: space-between;
  158. }
  159. }
  160. }
  161. </style>

四、优化axios响应拦截器与alert

1、axios响应拦截器

2.1 request.js 

(上图右侧的文件名错误)

  1. // 定制请求实例
  2. //导入axios npm install axios
  3. import axios from 'axios';
  4. //定义一个变量,记录公共的前缀baseURL
  5. // const baseURL = 'http://localhost:8080'
  6. const baseURL = '/api' // 注释上面代码,解决跨域问题
  7. const instance = axios.create({baseURL})
  8. // 添加响应拦截器
  9. instance.interceptors.response.use(
  10. result=>{
  11. // 判断业务状态码
  12. if(result.data.code === 1){
  13. //成功,正常返回数据
  14. return result.data;
  15. }
  16. // 操作失败
  17. alert(result.data.msg?result.data.msg : '服务异常')
  18. // 异步操作的状态转换为失败
  19. return Promise.reject(result.data)
  20. },
  21. err=>{
  22. alert('服务异常')
  23. return Promise.reject(err);//异步的状态转化成失败的状态
  24. }
  25. )
  26. export default instance;

2.2 优化Login.vue

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //控制注册与登录表单的显示, 默认显示注册
  7. const isRegister = ref(false)
  8. //二 注册 2.1定义数据模型
  9. const registerData = ref({
  10. username:'',
  11. password:'',
  12. rePassword:''
  13. })
  14. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  15. const checkRePassword = (rule,value,callback)=>{
  16. if(value === '' ){
  17. callback(new Error('请再次确认密码!'))
  18. }else if(value !== registerData.value.password){
  19. callback(new Error('请确保两次密码输入一致性!'))
  20. }else{
  21. callback() //校验通过
  22. }
  23. }
  24. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  25. const rules = {
  26. username:[
  27. {required:true,message:'请输入用户名!',trigger:'blur'},
  28. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  29. ],
  30. password:[
  31. {required:true,message:'请输入密码!',trigger:'blur'},
  32. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  33. ],
  34. rePassword:[
  35. {validator:checkRePassword,trigger:'blur'}
  36. ]
  37. }
  38. // 二 注册 3.3 调用后台接口,完成注册
  39. const register = async()=>{
  40. // registerData 是一个响应式对象,如果要获取值需要.value
  41. let result = await userRegisterService(registerData.value);
  42. /* 使用axios的 request.js 统一处理了,优化这里代码
  43. if(result.code ===1){
  44. //注册成功
  45. alert(result.msg?result.msg : '注册成功')
  46. }else{
  47. // 注册失败
  48. alert('注册失败')
  49. } */
  50. alert(result.msg?result.msg : '注册成功')
  51. }
  52. // 三 登录 1 绑定数据 复用注册表单的数据模型
  53. // 三 登录 2 数据校验 复用注册表单的数据校验
  54. // 三 登录 3 登录函数
  55. const login = async()=>{
  56. //调用接口完成登录
  57. let result = await userLoginService(registerData.value);
  58. /* 使用axios的 request.js 统一处理了,优化这里代码
  59. if(result.code ===1){
  60. //登录成功
  61. alert(result.msg?result.msg : '登录成功')
  62. }else{
  63. // 登录失败
  64. alert('登录失败')
  65. }*/
  66. alert(result.msg?result.msg : '登录成功')
  67. }
  68. // 三 登录 4 定义函数清空数据模型数据(将数据清空)
  69. const clearRegisterDate = ()=>{
  70. registerData.value={
  71. username:'',
  72. password:'',
  73. rePassword:''
  74. }
  75. }
  76. </script>
  77. <template>
  78. <el-row class="login-page">
  79. <el-col :span="12" class="bg"></el-col>
  80. <el-col :span="6" :offset="3" class="form">
  81. <!-- 注册表单 -->
  82. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  83. <el-form-item>
  84. <h1>注册</h1>
  85. </el-form-item>
  86. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  87. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  88. </el-form-item>
  89. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  90. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  91. </el-form-item>
  92. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  93. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  94. </el-form-item>
  95. <!-- 注册按钮 -->
  96. <el-form-item>
  97. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  98. 注册
  99. </el-button>
  100. </el-form-item>
  101. <el-form-item class="flex">
  102. <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  103. ← 返回
  104. </el-link>
  105. </el-form-item>
  106. </el-form>
  107. <!-- 登录表单 -->
  108. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  109. <el-form-item>
  110. <h1>登录</h1>
  111. </el-form-item>
  112. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  113. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  114. </el-form-item>
  115. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  116. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  117. </el-form-item>
  118. <el-form-item class="flex">
  119. <div class="flex">
  120. <el-checkbox>记住我</el-checkbox>
  121. <el-link type="primary" :underline="false">忘记密码?</el-link>
  122. </div>
  123. </el-form-item>
  124. <!-- 登录按钮 -->
  125. <el-form-item>
  126. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  127. </el-form-item>
  128. <el-form-item class="flex">
  129. <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  130. 注册 →
  131. </el-link>
  132. </el-form-item>
  133. </el-form>
  134. </el-col>
  135. </el-row>
  136. </template>
  137. <style lang="scss" scoped>
  138. /* 样式 */
  139. .login-page {
  140. height: 100vh;
  141. background-color: #fff;
  142. .bg {
  143. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  144. url('@/assets/login_bg.jpg') no-repeat center / cover;
  145. border-radius: 0 20px 20px 0;
  146. }
  147. .form {
  148. display: flex;
  149. flex-direction: column;
  150. justify-content: center;
  151. user-select: none;
  152. .title {
  153. margin: 0 auto;
  154. }
  155. .button {
  156. width: 100%;
  157. }
  158. .flex {
  159. width: 100%;
  160. display: flex;
  161. justify-content: space-between;
  162. }
  163. }
  164. }
  165. </style>

2、使用element-plus优化alert

2.1 request.js引用ElMessage 组件处理

  1. // 定制请求实例
  2. //导入axios npm install axios
  3. import axios from 'axios';
  4. //4.2 element-plus封装的组件
  5. import { ElMessage } from 'element-plus';
  6. //定义一个变量,记录公共的前缀baseURL
  7. // const baseURL = 'http://localhost:8080'
  8. const baseURL = '/api' // 注释上面代码,解决跨域问题
  9. const instance = axios.create({baseURL})
  10. // 添加响应拦截器
  11. instance.interceptors.response.use(
  12. result=>{
  13. //4.1 判断业务状态码
  14. if(result.data.code === 1){
  15. //成功,正常返回数据
  16. return result.data;
  17. }
  18. // 操作失败
  19. // alert(result.data.msg?result.data.msg : '服务异常')
  20. //4.2 优化alert
  21. ElMessage.error(result.data.msg?result.data.msg : '服务异常')
  22. // 异步操作的状态转换为失败
  23. return Promise.reject(result.data)
  24. },
  25. err=>{
  26. alert('服务异常')
  27. return Promise.reject(err);//异步的状态转化成失败的状态
  28. }
  29. )
  30. export default instance;

2.2  Login.vue引用ElMessage 组件处理

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //4.2 element-plus封装的组件
  7. import { ElMessage } from 'element-plus';
  8. //控制注册与登录表单的显示, 默认显示注册
  9. const isRegister = ref(false)
  10. //二 注册 2.1定义数据模型
  11. const registerData = ref({
  12. username:'',
  13. password:'',
  14. rePassword:''
  15. })
  16. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  17. const checkRePassword = (rule,value,callback)=>{
  18. if(value === '' ){
  19. callback(new Error('请再次确认密码!'))
  20. }else if(value !== registerData.value.password){
  21. callback(new Error('请确保两次密码输入一致性!'))
  22. }else{
  23. callback() //校验通过
  24. }
  25. }
  26. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  27. const rules = {
  28. username:[
  29. {required:true,message:'请输入用户名!',trigger:'blur'},
  30. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  31. ],
  32. password:[
  33. {required:true,message:'请输入密码!',trigger:'blur'},
  34. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  35. ],
  36. rePassword:[
  37. {validator:checkRePassword,trigger:'blur'}
  38. ]
  39. }
  40. // 二 注册 3.3 调用后台接口,完成注册
  41. const register = async()=>{
  42. // registerData 是一个响应式对象,如果要获取值需要.value
  43. let result = await userRegisterService(registerData.value);
  44. /* 使用axios的 request.js 统一处理了,优化这里代码
  45. if(result.code ===1){
  46. //注册成功
  47. alert(result.msg?result.msg : '注册成功')
  48. }else{
  49. // 注册失败
  50. alert('注册失败')
  51. } */
  52. //4.2 优化alert
  53. // alert(result.msg?result.msg : '注册成功')
  54. ElMessage.success(result.msg?result.msg : '注册成功')
  55. }
  56. // 三 登录 1 绑定数据 复用注册表单的数据模型
  57. // 三 登录 2 数据校验 复用注册表单的数据校验
  58. // 三 登录 3 登录函数
  59. const login = async()=>{
  60. //调用接口完成登录
  61. let result = await userLoginService(registerData.value);
  62. /* 使用axios的 request.js 统一处理了,优化这里代码
  63. if(result.code ===1){
  64. //登录成功
  65. alert(result.msg?result.msg : '登录成功')
  66. }else{
  67. // 登录失败
  68. alert('登录失败')
  69. }*/
  70. //4.2 优化alert
  71. // alert(result.msg?result.msg : '登录成功')
  72. ElMessage.success(result.msg?result.msg : '登录成功')
  73. }
  74. // 三 登录 4 定义函数清空数据模型数据(将数据清空)
  75. const clearRegisterDate = ()=>{
  76. registerData.value={
  77. username:'',
  78. password:'',
  79. rePassword:''
  80. }
  81. }
  82. </script>
  83. <template>
  84. <el-row class="login-page">
  85. <el-col :span="12" class="bg"></el-col>
  86. <el-col :span="6" :offset="3" class="form">
  87. <!-- 注册表单 -->
  88. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  89. <el-form-item>
  90. <h1>注册</h1>
  91. </el-form-item>
  92. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  93. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  94. </el-form-item>
  95. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  96. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  97. </el-form-item>
  98. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  99. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  100. </el-form-item>
  101. <!-- 注册按钮 -->
  102. <el-form-item>
  103. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  104. 注册
  105. </el-button>
  106. </el-form-item>
  107. <el-form-item class="flex">
  108. <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  109. ← 返回
  110. </el-link>
  111. </el-form-item>
  112. </el-form>
  113. <!-- 登录表单 -->
  114. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  115. <el-form-item>
  116. <h1>登录</h1>
  117. </el-form-item>
  118. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  119. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  120. </el-form-item>
  121. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  122. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  123. </el-form-item>
  124. <el-form-item class="flex">
  125. <div class="flex">
  126. <el-checkbox>记住我</el-checkbox>
  127. <el-link type="primary" :underline="false">忘记密码?</el-link>
  128. </div>
  129. </el-form-item>
  130. <!-- 登录按钮 -->
  131. <el-form-item>
  132. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  133. </el-form-item>
  134. <el-form-item class="flex">
  135. <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  136. 注册 →
  137. </el-link>
  138. </el-form-item>
  139. </el-form>
  140. </el-col>
  141. </el-row>
  142. </template>
  143. <style lang="scss" scoped>
  144. /* 样式 */
  145. .login-page {
  146. height: 100vh;
  147. background-color: #fff;
  148. .bg {
  149. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  150. url('@/assets/login_bg.jpg') no-repeat center / cover;
  151. border-radius: 0 20px 20px 0;
  152. }
  153. .form {
  154. display: flex;
  155. flex-direction: column;
  156. justify-content: center;
  157. user-select: none;
  158. .title {
  159. margin: 0 auto;
  160. }
  161. .button {
  162. width: 100%;
  163. }
  164. .flex {
  165. width: 100%;
  166. display: flex;
  167. justify-content: space-between;
  168. }
  169. }
  170. }
  171. </style>

五、主页面布局 

1、Layout页面

1.1 views下新增Layout.vue

  1. <script setup>
  2. import {
  3. Management,
  4. Promotion,
  5. UserFilled,
  6. User,
  7. Crop,
  8. EditPen,
  9. SwitchButton,
  10. CaretBottom
  11. } from '@element-plus/icons-vue'
  12. import avatar from '@/assets/default.png'
  13. </script>
  14. <template>
  15. <!-- element-plus 中的容器 -->
  16. <el-container class="layout-container">
  17. <!-- 左侧菜单 -->
  18. <el-aside width="200px">
  19. <div class="el-aside__logo"></div>
  20. <!-- element-plus 菜单标签 -->
  21. <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
  22. router>
  23. <el-menu-item >
  24. <el-icon>
  25. <Management />
  26. </el-icon>
  27. <span>文章分类</span>
  28. </el-menu-item>
  29. <el-menu-item >
  30. <el-icon>
  31. <Promotion />
  32. </el-icon>
  33. <span>文章管理</span>
  34. </el-menu-item>
  35. <el-sub-menu >
  36. <template #title>
  37. <el-icon>
  38. <UserFilled />
  39. </el-icon>
  40. <span>个人中心</span>
  41. </template>
  42. <el-menu-item >
  43. <el-icon>
  44. <User />
  45. </el-icon>
  46. <span>基本资料</span>
  47. </el-menu-item>
  48. <el-menu-item >
  49. <el-icon>
  50. <Crop />
  51. </el-icon>
  52. <span>更换头像</span>
  53. </el-menu-item>
  54. <el-menu-item >
  55. <el-icon>
  56. <EditPen />
  57. </el-icon>
  58. <span>重置密码</span>
  59. </el-menu-item>
  60. </el-sub-menu>
  61. </el-menu>
  62. </el-aside>
  63. <!-- 右侧主区域 -->
  64. <el-container>
  65. <!-- 头部区域 -->
  66. <el-header>
  67. <div>编码集中营:<strong>春天的菠菜</strong></div>
  68. <el-dropdown placement="bottom-end">
  69. <span class="el-dropdown__box">
  70. <el-avatar :src="avatar" />
  71. <el-icon>
  72. <CaretBottom />
  73. </el-icon>
  74. </span>
  75. <template #dropdown>
  76. <el-dropdown-menu>
  77. <el-dropdown-item command="profile" :icon="User">基本资料</el-dropdown-item>
  78. <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
  79. <el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item>
  80. <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
  81. </el-dropdown-menu>
  82. </template>
  83. </el-dropdown>
  84. </el-header>
  85. <!-- 中间区域 -->
  86. <el-main>
  87. <div style="width: 1290px; height: 570px;border: 1px solid red;">
  88. 内容展示区
  89. </div>
  90. </el-main>
  91. <!-- 底部区域 -->
  92. <el-footer>国际大事件 ©2023 Created by 春天的菠菜</el-footer>
  93. </el-container>
  94. </el-container>
  95. </template>
  96. <style lang="scss" scoped>
  97. .layout-container {
  98. height: 100vh;
  99. .el-aside {
  100. background-color: #232323;
  101. &__logo {
  102. height: 120px;
  103. background: url('@/assets/logo.png') no-repeat center / 120px auto;
  104. }
  105. .el-menu {
  106. border-right: none;
  107. }
  108. }
  109. .el-header {
  110. background-color: #fff;
  111. display: flex;
  112. align-items: center;
  113. justify-content: space-between;
  114. .el-dropdown__box {
  115. display: flex;
  116. align-items: center;
  117. .el-icon {
  118. color: #999;
  119. margin-left: 10px;
  120. }
  121. &:active,
  122. &:focus {
  123. outline: none;
  124. }
  125. }
  126. }
  127. .el-footer {
  128. display: flex;
  129. align-items: center;
  130. justify-content: center;
  131. font-size: 14px;
  132. color: #666;
  133. }
  134. }
  135. </style>

 1.2 App.vue导入Layout.vue

  1. <script setup>
  2. import LoginVue from '@/views/Login.vue'
  3. import LayoutVue from '@/views/Layout.vue';
  4. </script>
  5. <template>
  6. <LoginVue/>
  7. <!-- 五 LayoutVue-->
  8. <LayoutVue/>
  9. </template>
  10. <style scoped>
  11. </style>

2、路由

 

 2.1 安装vue-router

npm install vue-router@4

2.2 创建路由器index.js

src下新增router文件夹,在router下新增index.js

  1. import { createRouter, createWebHistory } from 'vue-router'
  2. //导入组件
  3. import LoginVue from '@/views/Login.vue'
  4. import LayoutVue from '@/views/Layout.vue'
  5. //定义路由关系
  6. const routes = [
  7. { path: '/login', component: LoginVue },
  8. { path: '/', component: LayoutVue }
  9. ]
  10. //创建路由器
  11. const router = createRouter({
  12. history: createWebHistory(),
  13. routes: routes
  14. })
  15. //导出路由
  16. export default router

2.3 在main.js使用vue-router

  1. import './assets/main.scss' // 本项目使用sass
  2. import { createApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. //2.3
  6. import router from '@/router'
  7. import App from './App.vue'
  8. const app = createApp(App)
  9. //2.3
  10. app.use(router)
  11. app.use(ElementPlus)
  12. app.mount('#app')

2.4 App.vue中声明router-view标签

  1. <script setup>
  2. // 五 2.4
  3. // import LoginVue from '@/views/Login.vue'
  4. // import LayoutVue from '@/views/Layout.vue';
  5. </script>
  6. <template>
  7. <!-- 五 2.4 -->
  8. <router-view></router-view>
  9. <!-- 五 2.4 -->
  10. <!-- <LoginVue/> -->
  11. <!-- 五 1.1 LayoutVue-->
  12. <LayoutVue/>
  13. </template>
  14. <style scoped>
  15. </style>

2.5  Login.vue优化登录成功跳转

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //4.2 element-plus封装的组件
  7. import { ElMessage } from 'element-plus';
  8. //2.5 导入路由
  9. import {useRouter} from 'vue-router'
  10. //2.5 调用路由
  11. const router = useRouter()
  12. //控制注册与登录表单的显示, 默认显示注册
  13. const isRegister = ref(false)
  14. //二 注册 2.1定义数据模型
  15. const registerData = ref({
  16. username:'',
  17. password:'',
  18. rePassword:''
  19. })
  20. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  21. const checkRePassword = (rule,value,callback)=>{
  22. if(value === '' ){
  23. callback(new Error('请再次确认密码!'))
  24. }else if(value !== registerData.value.password){
  25. callback(new Error('请确保两次密码输入一致性!'))
  26. }else{
  27. callback() //校验通过
  28. }
  29. }
  30. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  31. const rules = {
  32. username:[
  33. {required:true,message:'请输入用户名!',trigger:'blur'},
  34. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  35. ],
  36. password:[
  37. {required:true,message:'请输入密码!',trigger:'blur'},
  38. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  39. ],
  40. rePassword:[
  41. {validator:checkRePassword,trigger:'blur'}
  42. ]
  43. }
  44. // 二 注册 3.3 调用后台接口,完成注册
  45. const register = async()=>{
  46. // registerData 是一个响应式对象,如果要获取值需要.value
  47. let result = await userRegisterService(registerData.value);
  48. /* 使用axios的 request.js 统一处理了,优化这里代码
  49. if(result.code ===1){
  50. //注册成功
  51. alert(result.msg?result.msg : '注册成功')
  52. }else{
  53. // 注册失败
  54. alert('注册失败')
  55. } */
  56. //4.2 优化alert
  57. // alert(result.msg?result.msg : '注册成功')
  58. ElMessage.success(result.msg?result.msg : '注册成功')
  59. }
  60. // 三 登录 1 绑定数据 复用注册表单的数据模型
  61. // 三 登录 2 数据校验 复用注册表单的数据校验
  62. // 三 登录 3 登录函数
  63. const login = async()=>{
  64. //调用接口完成登录
  65. let result = await userLoginService(registerData.value);
  66. /* 使用axios的 request.js 统一处理了,优化这里代码
  67. if(result.code ===1){
  68. //登录成功
  69. alert(result.msg?result.msg : '登录成功')
  70. }else{
  71. // 登录失败
  72. alert('登录失败')
  73. }*/
  74. //4.2 优化alert
  75. // alert(result.msg?result.msg : '登录成功')
  76. ElMessage.success(result.msg?result.msg : '登录成功')
  77. //2.5 跳转首页 借助于路由
  78. router.push('/')
  79. }
  80. // 三 登录 4 定义函数清空数据模型数据(将数据清空)
  81. const clearRegisterDate = ()=>{
  82. registerData.value={
  83. username:'',
  84. password:'',
  85. rePassword:''
  86. }
  87. }
  88. </script>
  89. <template>
  90. <el-row class="login-page">
  91. <el-col :span="12" class="bg"></el-col>
  92. <el-col :span="6" :offset="3" class="form">
  93. <!-- 注册表单 -->
  94. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  95. <el-form-item>
  96. <h1>注册</h1>
  97. </el-form-item>
  98. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  99. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  100. </el-form-item>
  101. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  102. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  103. </el-form-item>
  104. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  105. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  106. </el-form-item>
  107. <!-- 注册按钮 -->
  108. <el-form-item>
  109. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  110. 注册
  111. </el-button>
  112. </el-form-item>
  113. <el-form-item class="flex">
  114. <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  115. ← 返回
  116. </el-link>
  117. </el-form-item>
  118. </el-form>
  119. <!-- 登录表单 -->
  120. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  121. <el-form-item>
  122. <h1>登录</h1>
  123. </el-form-item>
  124. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  125. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  126. </el-form-item>
  127. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  128. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  129. </el-form-item>
  130. <el-form-item class="flex">
  131. <div class="flex">
  132. <el-checkbox>记住我</el-checkbox>
  133. <el-link type="primary" :underline="false">忘记密码?</el-link>
  134. </div>
  135. </el-form-item>
  136. <!-- 登录按钮 -->
  137. <el-form-item>
  138. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  139. </el-form-item>
  140. <el-form-item class="flex">
  141. <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  142. 注册 →
  143. </el-link>
  144. </el-form-item>
  145. </el-form>
  146. </el-col>
  147. </el-row>
  148. </template>
  149. <style lang="scss" scoped>
  150. /* 样式 */
  151. .login-page {
  152. height: 100vh;
  153. background-color: #fff;
  154. .bg {
  155. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  156. url('@/assets/login_bg.jpg') no-repeat center / cover;
  157. border-radius: 0 20px 20px 0;
  158. }
  159. .form {
  160. display: flex;
  161. flex-direction: column;
  162. justify-content: center;
  163. user-select: none;
  164. .title {
  165. margin: 0 auto;
  166. }
  167. .button {
  168. width: 100%;
  169. }
  170. .flex {
  171. width: 100%;
  172. display: flex;
  173. justify-content: space-between;
  174. }
  175. }
  176. }
  177. </style>

2.6 测试验证

登录页面:   http://127.0.0.1:5173/login

3、子路由

 

3.1 views下创建vue文件 

 

3.1.1 ArticleCategory.vue
  1. <template>
  2. 文章分类
  3. </template>
3.1.2 ArticleManage.vue
  1. <template>
  2. 文章管理
  3. </template>
3.1.3 UserAvatar.vue
  1. <template>
  2. 更换头像
  3. </template>
3.1.4 UserInfo.vue
  1. <template>
  2. 基本资料
  3. </template>
3.1.5 UserResetPassword.vue
  1. <template>
  2. 重置密码
  3. </template>

3.2 index.js

  1. import { createRouter, createWebHistory } from 'vue-router'
  2. //导入组件
  3. import LoginVue from '@/views/Login.vue'
  4. import LayoutVue from '@/views/Layout.vue'
  5. import ArticleCategoryVue from '@/views/article/ArticleCategory.vue'
  6. import ArticleManageVue from '@/views/article/ArticleManage.vue'
  7. import UserAvatarVue from '@/views/user/UserAvatar.vue'
  8. import UserInfoVue from '@/views/user/UserInfo.vue'
  9. import UserResetPasswordVue from '@/views/user/UserResetPassword.vue'
  10. //定义路由关系
  11. const routes = [
  12. { path: '/login', component: LoginVue },
  13. {
  14. path: '/', component: LayoutVue,redirect:'/article/manage', children: [
  15. { path: '/article/category', component: ArticleCategoryVue },
  16. { path: '/article/manage', component: ArticleManageVue },
  17. { path: '/user/info', component: UserInfoVue },
  18. { path: '/user/avatar', component: UserAvatarVue },
  19. { path: '/user/resetPassword', component: UserResetPasswordVue }
  20. ]
  21. }
  22. ]
  23. //创建路由器
  24. const router = createRouter({
  25. history: createWebHistory(),
  26. routes: routes
  27. })
  28. //导出路由
  29. export default router

3.3 Layout.vue声明router-view标签

  1. <script setup>
  2. import {
  3. Management,
  4. Promotion,
  5. UserFilled,
  6. User,
  7. Crop,
  8. EditPen,
  9. SwitchButton,
  10. CaretBottom
  11. } from '@element-plus/icons-vue'
  12. import avatar from '@/assets/default.png'
  13. </script>
  14. <template>
  15. <!-- element-plus 中的容器 -->
  16. <el-container class="layout-container">
  17. <!-- 左侧菜单 -->
  18. <el-aside width="200px">
  19. <div class="el-aside__logo"></div>
  20. <!-- element-plus 菜单标签 -->
  21. <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
  22. router>
  23. <el-menu-item index="/article/category"> <!-- 五 3.3 -->
  24. <el-icon>
  25. <Management />
  26. </el-icon>
  27. <span>文章分类</span>
  28. </el-menu-item>
  29. <el-menu-item index="/article/manage"> <!-- 五 3.3 -->
  30. <el-icon>
  31. <Promotion />
  32. </el-icon>
  33. <span>文章管理</span>
  34. </el-menu-item>
  35. <el-sub-menu >
  36. <template #title>
  37. <el-icon>
  38. <UserFilled />
  39. </el-icon>
  40. <span>个人中心</span>
  41. </template>
  42. <el-menu-item index="/user/info"> <!-- 五 3.3 -->
  43. <el-icon>
  44. <User />
  45. </el-icon>
  46. <span>基本资料</span>
  47. </el-menu-item>
  48. <el-menu-item index="/user/avatar"> <!-- 五 3.3 -->
  49. <el-icon>
  50. <Crop />
  51. </el-icon>
  52. <span>更换头像</span>
  53. </el-menu-item>
  54. <el-menu-item index="/user/resetPassword"> <!-- 五 3.3 -->
  55. <el-icon>
  56. <EditPen />
  57. </el-icon>
  58. <span>重置密码</span>
  59. </el-menu-item>
  60. </el-sub-menu>
  61. </el-menu>
  62. </el-aside>
  63. <!-- 右侧主区域 -->
  64. <el-container>
  65. <!-- 头部区域 -->
  66. <el-header>
  67. <div>编码集中营:<strong>春天的菠菜</strong></div>
  68. <el-dropdown placement="bottom-end">
  69. <span class="el-dropdown__box">
  70. <el-avatar :src="avatar" />
  71. <el-icon>
  72. <CaretBottom />
  73. </el-icon>
  74. </span>
  75. <template #dropdown>
  76. <el-dropdown-menu>
  77. <el-dropdown-item command="profile" :icon="User">基本资料</el-dropdown-item>
  78. <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
  79. <el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item>
  80. <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
  81. </el-dropdown-menu>
  82. </template>
  83. </el-dropdown>
  84. </el-header>
  85. <!-- 中间区域 -->
  86. <el-main>
  87. <!-- 五 3.3 -->
  88. <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
  89. 内容展示区
  90. </div> -->
  91. <router-view></router-view>
  92. </el-main>
  93. <!-- 底部区域 -->
  94. <el-footer>国际大事件 ©2023 Created by 春天的菠菜</el-footer>
  95. </el-container>
  96. </el-container>
  97. </template>
  98. <style lang="scss" scoped>
  99. .layout-container {
  100. height: 100vh;
  101. .el-aside {
  102. background-color: #232323;
  103. &__logo {
  104. height: 120px;
  105. background: url('@/assets/logo.png') no-repeat center / 120px auto;
  106. }
  107. .el-menu {
  108. border-right: none;
  109. }
  110. }
  111. .el-header {
  112. background-color: #fff;
  113. display: flex;
  114. align-items: center;
  115. justify-content: space-between;
  116. .el-dropdown__box {
  117. display: flex;
  118. align-items: center;
  119. .el-icon {
  120. color: #999;
  121. margin-left: 10px;
  122. }
  123. &:active,
  124. &:focus {
  125. outline: none;
  126. }
  127. }
  128. }
  129. .el-footer {
  130. display: flex;
  131. align-items: center;
  132. justify-content: center;
  133. font-size: 14px;
  134. color: #666;
  135. }
  136. }
  137. </style>

3.4 测试验证

六、文章分类 

1、列表查询

1.1 article.js

api下新建article.js

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 六 文章分类列表查询函数
  4. export const articleCategoryListService = (registerData) =>{
  5. return request.get('/category');
  6. }

1.2 ArticleCategory.vue

  1. <script setup>
  2. //1.2 声明一个异步函数
  3. import {articleCategoryListService} from '@/api/article.js'
  4. import {
  5. Edit,
  6. Delete
  7. } from '@element-plus/icons-vue'
  8. import { ref } from 'vue'
  9. const categorys = ref([
  10. {
  11. "id": 3,
  12. "categoryName": "美食",
  13. "categoryAlias": "my",
  14. "createTime": "2023-09-02 12:06:59",
  15. "updateTime": "2023-09-02 12:06:59"
  16. },
  17. {
  18. "id": 4,
  19. "categoryName": "娱乐",
  20. "categoryAlias": "yl",
  21. "createTime": "2023-09-02 12:08:16",
  22. "updateTime": "2023-09-02 12:08:16"
  23. },
  24. {
  25. "id": 5,
  26. "categoryName": "军事",
  27. "categoryAlias": "js",
  28. "createTime": "2023-09-02 12:08:33",
  29. "updateTime": "2023-09-02 12:08:33"
  30. }
  31. ])
  32. //1.2 声明一个异步函数
  33. const articleCategoryList = async()=>{
  34. let result = await articleCategoryListService()
  35. categorys.value = result.data;
  36. }
  37. articleCategoryList();
  38. </script>
  39. <template>
  40. <el-card class="page-container">
  41. <template #header>
  42. <div class="header">
  43. <span>文章分类</span>
  44. <div class="extra">
  45. <el-button type="primary">添加分类</el-button>
  46. </div>
  47. </div>
  48. </template>
  49. <el-table :data="categorys" style="width: 100%">
  50. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  51. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  52. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  53. <el-table-column label="操作" width="100">
  54. <template #default="{ row }">
  55. <el-button :icon="Edit" circle plain type="primary" ></el-button>
  56. <el-button :icon="Delete" circle plain type="danger"></el-button>
  57. </template>
  58. </el-table-column>
  59. <template #empty>
  60. <el-empty description="没有数据" />
  61. </template>
  62. </el-table>
  63. </el-card>
  64. </template>
  65. <style lang="scss" scoped>
  66. .page-container {
  67. min-height: 100%;
  68. box-sizing: border-box;
  69. .header {
  70. display: flex;
  71. align-items: center;
  72. justify-content: space-between;
  73. }
  74. }
  75. </style>

此时页面访问存在token问题

2、Pinia状态管理库

2.1 安装pinia

npm install pinia

2.2 main.js导入pinia

在main.js中,引入pinia,创建pinia实例,并调用vue应用实例的use方法使用pinia

  1. import './assets/main.scss' // 本项目使用sass
  2. import { createApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. //2.3
  6. import router from '@/router'
  7. import App from './App.vue'
  8. //2.2
  9. import {createPinia} from 'pinia'
  10. const app = createApp(App)
  11. //2.2
  12. const pinia = createPinia();
  13. app.use(pinia)
  14. //2.3
  15. app.use(router)
  16. app.use(ElementPlus)
  17. app.mount('#app')

2.3 定义store

在src/stores目录下定义token.js

  1. //定义store
  2. import {defineStore} from 'pinia'
  3. import {ref} from 'vue'
  4. /*
  5. 第一个参数:名字,唯一性
  6. 第二个参数:函数,函数的内部可以定义状态的所有内容
  7. 返回值: 函数
  8. */
  9. export const useTokenStore = defineStore('token',()=>{
  10. //定义状态的内容
  11. //1.响应式变量
  12. const token = ref('')
  13. //2.定义一个函数,修改token的值
  14. const setToken = (newToken)=>{
  15. token.value = newToken
  16. }
  17. //3.函数,移除token的值
  18. const removeToken = ()=>{
  19. token.value=''
  20. }
  21. return {
  22. token,setToken,removeToken
  23. }
  24. });

2.4 使用Store

在需要使用状态的地方,导入@/stores/*.js , 使用即可

在Login.vue中导入@/stores/token.js, 并且当用户登录成功后,将token保存pinia中

  1. <script setup>
  2. import { User, Lock } from '@element-plus/icons-vue'
  3. import { ref } from 'vue'
  4. //二 注册 3.3 导入注册的接口 //三 登录 3.3 导入登录的接口
  5. import { userRegisterService,userLoginService} from '@/api/user.js'
  6. //4.2 element-plus封装的组件
  7. import { ElMessage } from 'element-plus';
  8. //2.5 导入路由
  9. import {useRouter} from 'vue-router'
  10. //2.4 导入token状态
  11. import { useTokenStore } from '@/stores/token.js'
  12. //2.5 调用路由
  13. const router = useRouter()
  14. //2.4 调用useTokenStore得到状态
  15. const tokenStore = useTokenStore();
  16. //控制注册与登录表单的显示, 默认显示注册
  17. const isRegister = ref(false)
  18. //二 注册 2.1定义数据模型
  19. const registerData = ref({
  20. username:'',
  21. password:'',
  22. rePassword:''
  23. })
  24. //二 注册 2.2自定义rePassword需要自定义校验规则校验规则的函数,三个参rule 规则,value 值,callback 回调函数
  25. const checkRePassword = (rule,value,callback)=>{
  26. if(value === '' ){
  27. callback(new Error('请再次确认密码!'))
  28. }else if(value !== registerData.value.password){
  29. callback(new Error('请确保两次密码输入一致性!'))
  30. }else{
  31. callback() //校验通过
  32. }
  33. }
  34. //二 注册 2.2 定义表单校验规则,rePassword需要自定义校验规则
  35. const rules = {
  36. username:[
  37. {required:true,message:'请输入用户名!',trigger:'blur'},
  38. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  39. ],
  40. password:[
  41. {required:true,message:'请输入密码!',trigger:'blur'},
  42. {min:5,max:16,message:'长度为5-16位非空字符',trigger:'blur'}
  43. ],
  44. rePassword:[
  45. {validator:checkRePassword,trigger:'blur'}
  46. ]
  47. }
  48. // 二 注册 3.3 调用后台接口,完成注册
  49. const register = async()=>{
  50. // registerData 是一个响应式对象,如果要获取值需要.value
  51. let result = await userRegisterService(registerData.value);
  52. /* 使用axios的 request.js 统一处理了,优化这里代码
  53. if(result.code ===1){
  54. //注册成功
  55. alert(result.msg?result.msg : '注册成功')
  56. }else{
  57. // 注册失败
  58. alert('注册失败')
  59. } */
  60. //4.2 优化alert
  61. // alert(result.msg?result.msg : '注册成功')
  62. ElMessage.success(result.msg?result.msg : '注册成功')
  63. }
  64. // 三 登录 1 绑定数据 复用注册表单的数据模型
  65. // 三 登录 2 数据校验 复用注册表单的数据校验
  66. // 三 登录 3 登录函数
  67. const login = async()=>{
  68. //调用接口完成登录
  69. let result = await userLoginService(registerData.value);
  70. /* 使用axios的 request.js 统一处理了,优化这里代码
  71. if(result.code ===1){
  72. //登录成功
  73. alert(result.msg?result.msg : '登录成功')
  74. }else{
  75. // 登录失败
  76. alert('登录失败')
  77. }*/
  78. //4.2 优化alert
  79. // alert(result.msg?result.msg : '登录成功')
  80. ElMessage.success(result.msg?result.msg : '登录成功')
  81. //2.4 保存token存储到pinia
  82. tokenStore.setToken(result.data)
  83. //2.5 跳转首页 借助于路由
  84. router.push('/')
  85. }
  86. // 三 登录 4 定义函数清空数据模型数据(将数据清空)
  87. const clearRegisterDate = ()=>{
  88. registerData.value={
  89. username:'',
  90. password:'',
  91. rePassword:''
  92. }
  93. }
  94. </script>
  95. <template>
  96. <el-row class="login-page">
  97. <el-col :span="12" class="bg"></el-col>
  98. <el-col :span="6" :offset="3" class="form">
  99. <!-- 注册表单 -->
  100. <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules"> <!-- 二 注册2.1 :model="registerData"表单声明属性 --> <!-- 二 注册2.2 :rules="rules"绑定校验 -->
  101. <el-form-item>
  102. <h1>注册</h1>
  103. </el-form-item>
  104. <el-form-item prop="username"> <!--二 注册 2.2 prop="username"绑定校验 -->
  105. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--二 注册 2.1 v-model="registerData.username"绑定属性 -->
  106. </el-form-item>
  107. <el-form-item prop="password"> <!-- 二 注册2.2 prop="password"绑定校验 -->
  108. <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!-- 二 注册2.1 v-model="registerData.password"绑定属性 -->
  109. </el-form-item>
  110. <el-form-item prop="rePassword"> <!-- 2.2 prop="rePassword"绑定校验 -->
  111. <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input> <!-- 二 注册2.1 v-model="registerData.rePassword"绑定属性 -->
  112. </el-form-item>
  113. <!-- 注册按钮 -->
  114. <el-form-item>
  115. <el-button class="button" type="primary" auto-insert-space @click="register"> <!-- 二 注册3.3 @click="register" 绑定注册单击事件 -->
  116. 注册
  117. </el-button>
  118. </el-form-item>
  119. <el-form-item class="flex">
  120. <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  121. ← 返回
  122. </el-link>
  123. </el-form-item>
  124. </el-form>
  125. <!-- 登录表单 -->
  126. <el-form ref="form" size="large" autocomplete="off" v-else model="registerDate" rules="rules"> <!-- 三 登录 3.1 :model="registerData"表单声明属性,复用注册 --> <!-- 三 登录 3.2 :rules="rules"绑定校验 -->
  127. <el-form-item>
  128. <h1>登录</h1>
  129. </el-form-item>
  130. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  131. <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input> <!--三 登录 3.1 v-model="registerData.username"绑定属性 -->
  132. </el-form-item>
  133. <el-form-item prop="username"> <!--三 登录 3.2 prop="username"绑定校验 -->
  134. <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input> <!--三 登录 3.1 v-model="registerData.password"绑定属性 -->
  135. </el-form-item>
  136. <el-form-item class="flex">
  137. <div class="flex">
  138. <el-checkbox>记住我</el-checkbox>
  139. <el-link type="primary" :underline="false">忘记密码?</el-link>
  140. </div>
  141. </el-form-item>
  142. <!-- 登录按钮 -->
  143. <el-form-item>
  144. <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
  145. </el-form-item>
  146. <el-form-item class="flex">
  147. <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterDate()"> <!--三 登录 4 调用函数clearRegisterDate() 清空数据 -->
  148. 注册 →
  149. </el-link>
  150. </el-form-item>
  151. </el-form>
  152. </el-col>
  153. </el-row>
  154. </template>
  155. <style lang="scss" scoped>
  156. /* 样式 */
  157. .login-page {
  158. height: 100vh;
  159. background-color: #fff;
  160. .bg {
  161. background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
  162. url('@/assets/login_bg.jpg') no-repeat center / cover;
  163. border-radius: 0 20px 20px 0;
  164. }
  165. .form {
  166. display: flex;
  167. flex-direction: column;
  168. justify-content: center;
  169. user-select: none;
  170. .title {
  171. margin: 0 auto;
  172. }
  173. .button {
  174. width: 100%;
  175. }
  176. .flex {
  177. width: 100%;
  178. display: flex;
  179. justify-content: space-between;
  180. }
  181. }
  182. }
  183. </style>

在article.js中导入@/stores/token.js, 从pinia中获取到存储的token,在发起查询文章分类列表的时候把token通过请求头的形式携带给服务器

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. const tokenStore = useTokenStore()
  9. //通过请求头Authorization携带token
  10. return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  11. }

2.5 测试验证

 3、 使用axios请求拦截器解决token繁琐问题

当进入主页后,将来要与后台交互,都需要携带token,如果每次请求都写这样的代码,将会比较繁琐,此时可以将携带token的代码通过请求拦截器统一处理

 3.1 request.js添加请求拦截器

在 src/util/request.js中

  1. // 定制请求实例
  2. //导入axios npm install axios
  3. import axios from 'axios';
  4. //4.2 element-plus封装的组件
  5. import { ElMessage } from 'element-plus';
  6. //3 导入token状态
  7. import { useTokenStore } from '@/stores/token.js';
  8. //定义一个变量,记录公共的前缀baseURL
  9. // const baseURL = 'http://localhost:8080'
  10. const baseURL = '/api' // 注释上面代码,解决跨域问题
  11. const instance = axios.create({baseURL})
  12. //3 添加请求拦截器
  13. instance.interceptors.request.use(
  14. (config)=>{
  15. //在发送请求之前做什么
  16. let tokenStore = useTokenStore()
  17. //如果token中有值,在携带
  18. if(tokenStore.token){
  19. config.headers.Authorization=tokenStore.token
  20. }
  21. return config
  22. },
  23. (err)=>{
  24. //如果请求错误做什么
  25. Promise.reject(err)
  26. }
  27. )
  28. // 添加响应拦截器
  29. instance.interceptors.response.use(
  30. result=>{
  31. //4.1 判断业务状态码
  32. if(result.data.code === 1){
  33. //成功,正常返回数据
  34. return result.data;
  35. }
  36. // 操作失败
  37. // alert(result.data.msg?result.data.msg : '服务异常')
  38. //4.2 优化alert
  39. ElMessage.error(result.data.msg?result.data.msg : '服务异常')
  40. // 异步操作的状态转换为失败
  41. return Promise.reject(result.data)
  42. },
  43. err=>{
  44. alert('服务异常')
  45. return Promise.reject(err);//异步的状态转化成失败的状态
  46. }
  47. )
  48. export default instance;

3.2 article.js移除之前添加的请求头

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }

4、pinia-persistedstate-plugin持久化插件

4.1 安装

npm install pinia-persistedstate-plugin

4.2 pinia中使用persist插件

在main.js中

  1. import './assets/main.scss' // 本项目使用sass
  2. import { createApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. //2.3
  6. import router from '@/router'
  7. import App from './App.vue'
  8. //2.2
  9. import {createPinia} from 'pinia'
  10. //4.2 导入持久化插件
  11. import {createPersistedState} from'pinia-persistedstate-plugin'
  12. const app = createApp(App)
  13. //2.2
  14. const pinia = createPinia();
  15. //4.2
  16. const persist = createPersistedState()
  17. //4.2 pinia使用持久化插件
  18. pinia.use(persist)
  19. app.use(pinia)
  20. //2.3
  21. app.use(router)
  22. app.use(ElementPlus)
  23. app.mount('#app')

4.3 在创建定义状态是配置持久化

在src/stores/token.js中

  1. //定义store
  2. import {defineStore} from 'pinia'
  3. import {ref} from 'vue'
  4. /*
  5. 第一个参数:名字,唯一性
  6. 第二个参数:函数,函数的内部可以定义状态的所有内容
  7. 返回值: 函数
  8. */
  9. export const useTokenStore = defineStore('token',()=>{
  10. //定义状态的内容
  11. //1.响应式变量
  12. const token = ref('')
  13. //2.定义一个函数,修改token的值
  14. const setToken = (newToken)=>{
  15. token.value = newToken
  16. }
  17. //3.函数,移除token的值
  18. const removeToken = ()=>{
  19. token.value=''
  20. }
  21. return {
  22. token,setToken,removeToken
  23. }
  24. },{
  25. persist:true//4.3持久化存储
  26. });

5、未登录统一处理

在后续访问接口时,如果没有登录,则前端不携带token,后台服务器会返回响应状态码401,代表未登录,此时可以在axios的响应拦截器中,统一对未登录的情况做处理request.js

  1. // 定制请求实例
  2. //导入axios npm install axios
  3. import axios from 'axios';
  4. //4.2 element-plus封装的组件
  5. import { ElMessage } from 'element-plus';
  6. //3.1 导入token状态
  7. import { useTokenStore } from '@/stores/token.js';
  8. //5 导入路由跳转到首页
  9. import router from '@/router'
  10. //定义一个变量,记录公共的前缀baseURL
  11. // const baseURL = 'http://localhost:8080'
  12. const baseURL = '/api' // 注释上面代码,解决跨域问题
  13. const instance = axios.create({baseURL})
  14. //3 添加请求拦截器
  15. instance.interceptors.request.use(
  16. (config)=>{
  17. //在发送请求之前做什么
  18. let tokenStore = useTokenStore()
  19. //如果token中有值,在携带
  20. if(tokenStore.token){
  21. config.headers.Authorization=tokenStore.token
  22. }
  23. return config
  24. },
  25. (err)=>{
  26. //如果请求错误做什么
  27. Promise.reject(err)
  28. }
  29. )
  30. // 添加响应拦截器
  31. instance.interceptors.response.use(
  32. result=>{
  33. //4.1 判断业务状态码
  34. if(result.data.code === 1){
  35. //成功,正常返回数据
  36. return result.data;
  37. }
  38. // 操作失败
  39. // alert(result.data.msg?result.data.msg : '服务异常')
  40. //4.2 优化alert
  41. // ElMessage.error(result.data.msg?result.data.msg : '服务异常')
  42. ElMessage.error(result.data.msg || '服务异常')
  43. // 异步操作的状态转换为失败
  44. return Promise.reject(result.data)
  45. },
  46. err=>{
  47. //5 如果响应状态码时401,代表未登录,给出对应的提示,并跳转到登录页
  48. if(err.response.status===401){
  49. ElMessage.error('请先登录!')
  50. router.push('/login')
  51. }else{
  52. ElMessage.error('服务异常');
  53. }
  54. return Promise.reject(err);//异步的状态转化成失败的状态
  55. }
  56. )
  57. export default instance;

6、添加文章分类

6.1  ArticleCategory.vue

添加弹窗分类、数据模型和校验规则、添加分类按钮单击事件,确认按钮单击事件、在页面中调用接口

  1. <script setup>
  2. //6.2 element-plus封装的组件
  3. import { ElMessage } from 'element-plus';
  4. //1.2 articleCategoryListService声明一个异步函数 6.2articleCategoryAddService
  5. import {articleCategoryListService,articleCategoryAddService} from '@/api/article.js'
  6. import {
  7. Edit,
  8. Delete
  9. } from '@element-plus/icons-vue'
  10. import { ref } from 'vue'
  11. const categorys = ref([
  12. {
  13. "id": 3,
  14. "categoryName": "美食",
  15. "categoryAlias": "my",
  16. "createTime": "2023-09-02 12:06:59",
  17. "updateTime": "2023-09-02 12:06:59"
  18. },
  19. {
  20. "id": 4,
  21. "categoryName": "娱乐",
  22. "categoryAlias": "yl",
  23. "createTime": "2023-09-02 12:08:16",
  24. "updateTime": "2023-09-02 12:08:16"
  25. },
  26. {
  27. "id": 5,
  28. "categoryName": "军事",
  29. "categoryAlias": "js",
  30. "createTime": "2023-09-02 12:08:33",
  31. "updateTime": "2023-09-02 12:08:33"
  32. }
  33. ])
  34. //1.2 声明一个异步函数
  35. const articleCategoryList = async()=>{
  36. let result = await articleCategoryListService()
  37. categorys.value = result.data;
  38. }
  39. articleCategoryList();
  40. //6.1 控制添加分类弹窗
  41. const dialogVisible = ref(false)
  42. //6.1 添加分类数据模型
  43. const categoryModel = ref({
  44. categoryName: '',
  45. categoryAlias: ''
  46. })
  47. //6.1 添加分类表单校验
  48. const rules = {
  49. categoryName: [
  50. { required: true, message: '请输入分类名称', trigger: 'blur' },
  51. ],
  52. categoryAlias: [
  53. { required: true, message: '请输入分类别名', trigger: 'blur' },
  54. ]
  55. }
  56. //6.1 调用接口添加表单
  57. const addCategory = async ()=>{
  58. let result = await articleCategoryAddService(categoryModel.value);
  59. ElMessage.success(result.message? result.message:'添加成功')
  60. //隐藏弹窗
  61. dialogVisible.value = false
  62. //再次访问后台接口,查询所有分类
  63. articleCategoryList()
  64. }
  65. </script>
  66. <template>
  67. <el-card class="page-container">
  68. <template #header>
  69. <div class="header">
  70. <span>文章分类</span>
  71. <div class="extra">
  72. <el-button type="primary" @click="dialogVisible = true">添加分类</el-button> <!-- 六 6.1 @click="dialogVisible = true"绑定点击事件-->
  73. </div>
  74. </div>
  75. </template>
  76. <el-table :data="categorys" style="width: 100%">
  77. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  78. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  79. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  80. <el-table-column label="创建时间" prop="createTime"></el-table-column>
  81. <el-table-column label="更新时间" prop="updateTime"></el-table-column>
  82. <el-table-column label="操作" width="100">
  83. <template #default="{ row }">
  84. <el-button :icon="Edit" circle plain type="primary" ></el-button>
  85. <el-button :icon="Delete" circle plain type="danger"></el-button>
  86. </template>
  87. </el-table-column>
  88. <template #empty>
  89. <el-empty description="没有数据" />
  90. </template>
  91. </el-table>
  92. <!-- 六 6.1 添加分类弹窗 -->
  93. <el-dialog v-model="dialogVisible" title="添加弹层" width="30%">
  94. <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
  95. <el-form-item label="分类名称" prop="categoryName">
  96. <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
  97. </el-form-item>
  98. <el-form-item label="分类别名" prop="categoryAlias">
  99. <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
  100. </el-form-item>
  101. </el-form>
  102. <template #footer>
  103. <span class="dialog-footer">
  104. <el-button @click="dialogVisible = false">取消</el-button>
  105. <el-button type="primary" @click="addCategory"> 确认 </el-button> <!-- 六 6.1 @click="addCategory"绑定点击事件-->
  106. </span>
  107. </template>
  108. </el-dialog>
  109. </el-card>
  110. </template>
  111. <style lang="scss" scoped>
  112. .page-container {
  113. min-height: 100%;
  114. box-sizing: border-box;
  115. .header {
  116. display: flex;
  117. align-items: center;
  118. justify-content: space-between;
  119. }
  120. }
  121. </style>

6.2 在article.js中提供添加分类的函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }

6.3 测试验证

7、修改文章分类 

分析编辑与新增的弹窗页面可以复用,优化实施

7.1 修改分类弹窗页面

修改分类弹窗和新增文章分类弹窗长的一样,所以可以复用添加分类的弹窗

7.1.1 弹窗标题显示  ArticleCategory.vue

定义标题

  1. //弹窗标题
  2. const title=ref('')
7.1.2 在弹窗上绑定标题 ArticleCategory.vue
 <el-dialog v-model="dialogVisible" :title="title" width="30%">
7.1.3 为添加分类按钮绑定事件 ArticleCategory.vue
<el-button type="primary" @click="title='添加分类';dialogVisible = true">添加分类</el-button>
7.1.4 为修改分类按钮绑定事件 ArticleCategory.vue
<el-button :icon="Edit" circle plain type="primary" @click="title='修改分类';dialogVisible=true"></el-button>

7.2 修改数据回显 ArticleCategory.vue

当点击修改分类按钮时,需要把当前这一条数据的详细信息显示到修改分类的弹窗上,这个叫回显

通过插槽的方式得到被点击按钮所在行的数据

  1. <script setup>
  2. //6.2 element-plus封装的组件
  3. import { ElMessage } from 'element-plus';
  4. //1.2 articleCategoryListService声明一个异步函数 6.2articleCategoryAddService
  5. import {articleCategoryListService,articleCategoryAddService} from '@/api/article.js'
  6. import {
  7. Edit,
  8. Delete
  9. } from '@element-plus/icons-vue'
  10. import { ref } from 'vue'
  11. const categorys = ref([
  12. {
  13. "id": 3,
  14. "categoryName": "美食",
  15. "categoryAlias": "my",
  16. "createTime": "2023-09-02 12:06:59",
  17. "updateTime": "2023-09-02 12:06:59"
  18. },
  19. {
  20. "id": 4,
  21. "categoryName": "娱乐",
  22. "categoryAlias": "yl",
  23. "createTime": "2023-09-02 12:08:16",
  24. "updateTime": "2023-09-02 12:08:16"
  25. },
  26. {
  27. "id": 5,
  28. "categoryName": "军事",
  29. "categoryAlias": "js",
  30. "createTime": "2023-09-02 12:08:33",
  31. "updateTime": "2023-09-02 12:08:33"
  32. }
  33. ])
  34. //1.2 声明一个异步函数
  35. const articleCategoryList = async()=>{
  36. let result = await articleCategoryListService()
  37. categorys.value = result.data;
  38. }
  39. articleCategoryList();
  40. //6.1 控制添加分类弹窗
  41. const dialogVisible = ref(false)
  42. //6.1 添加分类数据模型
  43. const categoryModel = ref({
  44. categoryName: '',
  45. categoryAlias: ''
  46. })
  47. //6.1 添加分类表单校验
  48. const rules = {
  49. categoryName: [
  50. { required: true, message: '请输入分类名称', trigger: 'blur' },
  51. ],
  52. categoryAlias: [
  53. { required: true, message: '请输入分类别名', trigger: 'blur' },
  54. ]
  55. }
  56. //6.1 调用接口添加表单
  57. const addCategory = async ()=>{
  58. let result = await articleCategoryAddService(categoryModel.value);
  59. ElMessage.success(result.message? result.message:'添加成功')
  60. //隐藏弹窗
  61. dialogVisible.value = false
  62. //再次访问后台接口,查询所有分类
  63. articleCategoryList()
  64. }
  65. //7.1.1 弹窗标题
  66. const title=ref('')
  67. //7.2展示编辑弹窗
  68. const showDialog = (row)=>{
  69. title.value = '修改分类';dialogVisible.value = true
  70. //数据拷贝
  71. categoryModel.value.categoryName = row.categoryName;
  72. categoryModel.value.categoryAlias = row.categoryAlias;
  73. //扩展id属性,将来需要传参给后台完成分类的修改
  74. categoryModel.value.id = row.id
  75. }
  76. </script>
  77. <template>
  78. <el-card class="page-container">
  79. <template #header>
  80. <div class="header">
  81. <span>文章分类</span>
  82. <div class="extra">
  83. <el-button type="primary" @click="title='添加分类';dialogVisible = true">添加分类</el-button> <!-- 六 6.1 @click="dialogVisible = true"绑定点击事件 六7.1.3 title='添加分类';-->
  84. </div>
  85. </div>
  86. </template>
  87. <el-table :data="categorys" style="width: 100%">
  88. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  89. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  90. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  91. <el-table-column label="创建时间" prop="createTime"></el-table-column>
  92. <el-table-column label="更新时间" prop="updateTime"></el-table-column>
  93. <el-table-column label="操作" width="100">
  94. <template #default="{ row }">
  95. <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> <!-- 六 7.1.4 @click="title='修改分类';dialogVisible=true"绑定事件 六 7.2 showDialog(row)-->
  96. <el-button :icon="Delete" circle plain type="danger"></el-button>
  97. </template>
  98. </el-table-column>
  99. <template #empty>
  100. <el-empty description="没有数据" />
  101. </template>
  102. </el-table>
  103. <!-- 六 6.1 添加分类弹窗 -->
  104. <el-dialog v-model="dialogVisible" :title="title" width="30%"> <!-- 六 7.1.2 :title="title"绑定标题-->
  105. <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
  106. <el-form-item label="分类名称" prop="categoryName">
  107. <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
  108. </el-form-item>
  109. <el-form-item label="分类别名" prop="categoryAlias">
  110. <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
  111. </el-form-item>
  112. </el-form>
  113. <template #footer>
  114. <span class="dialog-footer">
  115. <el-button @click="dialogVisible = false">取消</el-button>
  116. <el-button type="primary" @click="addCategory"> 确认 </el-button> <!-- 六 6.1 @click="addCategory"绑定点击事件-->
  117. </span>
  118. </template>
  119. </el-dialog>
  120. </el-card>
  121. </template>
  122. <style lang="scss" scoped>
  123. .page-container {
  124. min-height: 100%;
  125. box-sizing: border-box;
  126. .header {
  127. display: flex;
  128. align-items: center;
  129. justify-content: space-between;
  130. }
  131. }
  132. </style>

7.3 修改文章分类接口调用

7.3.1 article.js中提供修改分类的函数
  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
7.3.2 修改确定按钮的绑定事件 ArticleCategory.vue
  1. <span class="dialog-footer">
  2.                <el-button @click="dialogVisible = false">取消</el-button>
  3.                <el-button type="primary" @click="title==='添加分类'? addCategory():updateCategory()"> 确认 </el-button>
  4.            </span>
7.3.3 调用接口完成修改的函数  ArticleCategory.vue
  1. <script setup>
  2. //6.2 element-plus封装的组件
  3. import { ElMessage } from 'element-plus';
  4. //1.2 articleCategoryListService声明一个异步函数 6.2articleCategoryAddService 7.3.3 articleCategoryUpdateService
  5. import {articleCategoryListService,articleCategoryAddService,articleCategoryUpdateService} from '@/api/article.js'
  6. import {
  7. Edit,
  8. Delete
  9. } from '@element-plus/icons-vue'
  10. import { ref } from 'vue'
  11. const categorys = ref([
  12. {
  13. "id": 3,
  14. "categoryName": "美食",
  15. "categoryAlias": "my",
  16. "createTime": "2023-09-02 12:06:59",
  17. "updateTime": "2023-09-02 12:06:59"
  18. },
  19. {
  20. "id": 4,
  21. "categoryName": "娱乐",
  22. "categoryAlias": "yl",
  23. "createTime": "2023-09-02 12:08:16",
  24. "updateTime": "2023-09-02 12:08:16"
  25. },
  26. {
  27. "id": 5,
  28. "categoryName": "军事",
  29. "categoryAlias": "js",
  30. "createTime": "2023-09-02 12:08:33",
  31. "updateTime": "2023-09-02 12:08:33"
  32. }
  33. ])
  34. //1.2 声明一个异步函数
  35. const articleCategoryList = async()=>{
  36. let result = await articleCategoryListService()
  37. categorys.value = result.data;
  38. }
  39. articleCategoryList();
  40. //6.1 控制添加分类弹窗
  41. const dialogVisible = ref(false)
  42. //6.1 添加分类数据模型
  43. const categoryModel = ref({
  44. categoryName: '',
  45. categoryAlias: ''
  46. })
  47. //6.1 添加分类表单校验
  48. const rules = {
  49. categoryName: [
  50. { required: true, message: '请输入分类名称', trigger: 'blur' },
  51. ],
  52. categoryAlias: [
  53. { required: true, message: '请输入分类别名', trigger: 'blur' },
  54. ]
  55. }
  56. //6.1 调用接口添加表单
  57. const addCategory = async ()=>{
  58. let result = await articleCategoryAddService(categoryModel.value);
  59. ElMessage.success(result.message? result.message:'添加成功')
  60. //隐藏弹窗
  61. dialogVisible.value = false
  62. //再次访问后台接口,查询所有分类
  63. articleCategoryList()
  64. }
  65. //7.1.1 弹窗标题
  66. const title=ref('')
  67. //7.2展示编辑弹窗
  68. const showDialog = (row)=>{
  69. title.value = '修改分类';dialogVisible.value = true
  70. //数据拷贝
  71. categoryModel.value.categoryName = row.categoryName;
  72. categoryModel.value.categoryAlias = row.categoryAlias;
  73. //扩展id属性,将来需要传参给后台完成分类的修改
  74. categoryModel.value.id = row.id
  75. }
  76. //7.3.3修改分类
  77. const updateCategory=async ()=>{
  78. let result = await articleCategoryUpdateService(categoryModel.value)
  79. ElMessage.success(result.message? result.message:'修改成功')
  80. //隐藏弹窗
  81. dialogVisible.value=false
  82. //再次访问后台接口,查询所有分类
  83. articleCategoryList()
  84. }
  85. </script>
  86. <template>
  87. <el-card class="page-container">
  88. <template #header>
  89. <div class="header">
  90. <span>文章分类</span>
  91. <div class="extra">
  92. <el-button type="primary" @click="title='添加分类';dialogVisible = true">添加分类</el-button> <!-- 六 6.1 @click="dialogVisible = true"绑定点击事件 六7.1.3 title='添加分类';-->
  93. </div>
  94. </div>
  95. </template>
  96. <el-table :data="categorys" style="width: 100%">
  97. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  98. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  99. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  100. <el-table-column label="创建时间" prop="createTime"></el-table-column>
  101. <el-table-column label="更新时间" prop="updateTime"></el-table-column>
  102. <el-table-column label="操作" width="100">
  103. <template #default="{ row }">
  104. <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> <!-- 六 7.1.4 @click="title='修改分类';dialogVisible=true"绑定事件 六 7.2 showDialog(row)-->
  105. <el-button :icon="Delete" circle plain type="danger"></el-button>
  106. </template>
  107. </el-table-column>
  108. <template #empty>
  109. <el-empty description="没有数据" />
  110. </template>
  111. </el-table>
  112. <!-- 六 6.1 添加分类弹窗 -->
  113. <el-dialog v-model="dialogVisible" :title="title" width="30%"> <!-- 六 7.1.2 :title="title"绑定标题-->
  114. <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
  115. <el-form-item label="分类名称" prop="categoryName">
  116. <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
  117. </el-form-item>
  118. <el-form-item label="分类别名" prop="categoryAlias">
  119. <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
  120. </el-form-item>
  121. </el-form>
  122. <template #footer>
  123. <span class="dialog-footer">
  124. <el-button @click="dialogVisible = false">取消</el-button>
  125. <el-button type="primary" @click="title==='添加分类'? addCategory():updateCategory()"> 确认 </el-button> <!-- 六 6.1 @click="addCategory"绑定点击事件 六 7.3.1 @click="title==='添加分类'? addCategory():updateCategory()"-->
  126. </span>
  127. </template>
  128. </el-dialog>
  129. </el-card>
  130. </template>
  131. <style lang="scss" scoped>
  132. .page-container {
  133. min-height: 100%;
  134. box-sizing: border-box;
  135. .header {
  136. display: flex;
  137. align-items: center;
  138. justify-content: space-between;
  139. }
  140. }
  141. </style>
7.3.4 优化添加时数据回显

由于现在修改和新增共用了一个数据模型,所以在点击添加分类后,有时候会显示数据,此时可以将categoryModel中的数据清空

  1. //清空模型数据
  2. const clearCategoryModel = ()=>{
  3.    categoryModel.value.categoryName='',
  4.    categoryModel.value.categoryAlias=''
  5. }
  1. <script setup>
  2. //6.2 element-plus封装的组件
  3. import { ElMessage } from 'element-plus';
  4. //1.2 articleCategoryListService声明一个异步函数 6.2articleCategoryAddService 7.3.3 articleCategoryUpdateService
  5. import {articleCategoryListService,articleCategoryAddService,articleCategoryUpdateService} from '@/api/article.js'
  6. import {
  7. Edit,
  8. Delete
  9. } from '@element-plus/icons-vue'
  10. import { ref } from 'vue'
  11. const categorys = ref([
  12. {
  13. "id": 3,
  14. "categoryName": "美食",
  15. "categoryAlias": "my",
  16. "createTime": "2023-09-02 12:06:59",
  17. "updateTime": "2023-09-02 12:06:59"
  18. },
  19. {
  20. "id": 4,
  21. "categoryName": "娱乐",
  22. "categoryAlias": "yl",
  23. "createTime": "2023-09-02 12:08:16",
  24. "updateTime": "2023-09-02 12:08:16"
  25. },
  26. {
  27. "id": 5,
  28. "categoryName": "军事",
  29. "categoryAlias": "js",
  30. "createTime": "2023-09-02 12:08:33",
  31. "updateTime": "2023-09-02 12:08:33"
  32. }
  33. ])
  34. //1.2 声明一个异步函数
  35. const articleCategoryList = async()=>{
  36. let result = await articleCategoryListService()
  37. categorys.value = result.data;
  38. }
  39. articleCategoryList();
  40. //6.1 控制添加分类弹窗
  41. const dialogVisible = ref(false)
  42. //6.1 添加分类数据模型
  43. const categoryModel = ref({
  44. categoryName: '',
  45. categoryAlias: ''
  46. })
  47. //6.1 添加分类表单校验
  48. const rules = {
  49. categoryName: [
  50. { required: true, message: '请输入分类名称', trigger: 'blur' },
  51. ],
  52. categoryAlias: [
  53. { required: true, message: '请输入分类别名', trigger: 'blur' },
  54. ]
  55. }
  56. //6.1 调用接口添加表单
  57. const addCategory = async ()=>{
  58. let result = await articleCategoryAddService(categoryModel.value);
  59. ElMessage.success(result.message? result.message:'添加成功')
  60. //隐藏弹窗
  61. dialogVisible.value = false
  62. //再次访问后台接口,查询所有分类
  63. articleCategoryList()
  64. }
  65. //7.1.1 弹窗标题
  66. const title=ref('')
  67. //7.2展示编辑弹窗
  68. const showDialog = (row)=>{
  69. title.value = '修改分类';dialogVisible.value = true
  70. //数据拷贝
  71. categoryModel.value.categoryName = row.categoryName;
  72. categoryModel.value.categoryAlias = row.categoryAlias;
  73. //扩展id属性,将来需要传参给后台完成分类的修改
  74. categoryModel.value.id = row.id
  75. }
  76. //7.3.3修改分类
  77. const updateCategory=async ()=>{
  78. let result = await articleCategoryUpdateService(categoryModel.value)
  79. ElMessage.success(result.message? result.message:'修改成功')
  80. //隐藏弹窗
  81. dialogVisible.value=false
  82. //再次访问后台接口,查询所有分类
  83. articleCategoryList()
  84. }
  85. //7.3.4 清空模型数据
  86. const clearCategoryModel = ()=>{
  87. categoryModel.value.categoryName='',
  88. categoryModel.value.categoryAlias=''
  89. }
  90. </script>
  91. <template>
  92. <el-card class="page-container">
  93. <template #header>
  94. <div class="header">
  95. <span>文章分类</span>
  96. <div class="extra">
  97. <el-button type="primary" @click="title='添加分类';dialogVisible = true;clearCategoryModel()">添加分类</el-button> <!-- 六 6.1 @click="dialogVisible = true"绑定点击事件 六7.1.3 title='添加分类'; 六 7.3.4 清空模型数据 clearCategoryModel()-->
  98. </div>
  99. </div>
  100. </template>
  101. <el-table :data="categorys" style="width: 100%">
  102. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  103. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  104. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  105. <el-table-column label="创建时间" prop="createTime"></el-table-column>
  106. <el-table-column label="更新时间" prop="updateTime"></el-table-column>
  107. <el-table-column label="操作" width="100">
  108. <template #default="{ row }">
  109. <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> <!-- 六 7.1.4 @click="title='修改分类';dialogVisible=true"绑定事件 六 7.2 showDialog(row)-->
  110. <el-button :icon="Delete" circle plain type="danger"></el-button>
  111. </template>
  112. </el-table-column>
  113. <template #empty>
  114. <el-empty description="没有数据" />
  115. </template>
  116. </el-table>
  117. <!-- 六 6.1 添加分类弹窗 -->
  118. <el-dialog v-model="dialogVisible" :title="title" width="30%"> <!-- 六 7.1.2 :title="title"绑定标题-->
  119. <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
  120. <el-form-item label="分类名称" prop="categoryName">
  121. <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
  122. </el-form-item>
  123. <el-form-item label="分类别名" prop="categoryAlias">
  124. <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
  125. </el-form-item>
  126. </el-form>
  127. <template #footer>
  128. <span class="dialog-footer">
  129. <el-button @click="dialogVisible = false">取消</el-button>
  130. <el-button type="primary" @click="title==='添加分类'? addCategory():updateCategory()"> 确认 </el-button> <!-- 六 6.1 @click="addCategory"绑定点击事件 六 7.3.1 @click="title==='添加分类'? addCategory():updateCategory()"-->
  131. </span>
  132. </template>
  133. </el-dialog>
  134. </el-card>
  135. </template>
  136. <style lang="scss" scoped>
  137. .page-container {
  138. min-height: 100%;
  139. box-sizing: border-box;
  140. .header {
  141. display: flex;
  142. align-items: center;
  143. justify-content: space-between;
  144. }
  145. }
  146. </style>

8、删除文章分类

 8.1 删除接口

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
  22. //8.1 删除分类
  23. export const articleCategoryDeleteService = (id) => {
  24. return request.delete('/category?id='+id)
  25. }

8.2 删除确认框

  1. //删除分类 给删除按钮绑定事件
  2. const deleteCategory = (row) => {
  3. ElMessageBox.confirm(
  4. '你确认删除该分类信息吗?',
  5. '温馨提示',
  6. {
  7. confirmButtonText: '确认',
  8. cancelButtonText: '取消',
  9. type: 'warning',
  10. }
  11. )
  12. .then(() => {
  13. //用户点击了确认
  14. ElMessage({
  15. type: 'success',
  16. message: '删除成功',
  17. })
  18. })
  19. .catch(() => {
  20. //用户点击了取消
  21. ElMessage({
  22. type: 'info',
  23. message: '取消删除',
  24. })
  25. })
  26. }

 8.3 为删除按钮绑定事件

  1. <template #default="{ row }">
  2. <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> <!-- 六 7.1.4 @click="title='修改分类';dialogVisible=true"绑定事件 六 7.2 showDialog(row)-->
  3. <el-button :icon="Delete" circle plain type="danger" @click="deleteCategory(row)"></el-button> <!-- 六 8.3 @click="deleteCategory(row)" 绑定删除事件-->
  4. </template>

8.4 调用删除接口

  1. <script setup>
  2. //6.2 ElMessage element-plus封装的组件 六 8.2 ElMessageBox
  3. import { ElMessage,ElMessageBox } from 'element-plus';
  4. //1.2 articleCategoryListService声明一个异步函数 6.2articleCategoryAddService 7.3.3 articleCategoryUpdateService 8.2 articleCategoryDeleteService
  5. import {articleCategoryListService,articleCategoryAddService,articleCategoryUpdateService,articleCategoryDeleteService} from '@/api/article.js'
  6. import {
  7. Edit,
  8. Delete
  9. } from '@element-plus/icons-vue'
  10. import { ref } from 'vue'
  11. const categorys = ref([
  12. {
  13. "id": 3,
  14. "categoryName": "美食",
  15. "categoryAlias": "my",
  16. "createTime": "2023-09-02 12:06:59",
  17. "updateTime": "2023-09-02 12:06:59"
  18. },
  19. {
  20. "id": 4,
  21. "categoryName": "娱乐",
  22. "categoryAlias": "yl",
  23. "createTime": "2023-09-02 12:08:16",
  24. "updateTime": "2023-09-02 12:08:16"
  25. },
  26. {
  27. "id": 5,
  28. "categoryName": "军事",
  29. "categoryAlias": "js",
  30. "createTime": "2023-09-02 12:08:33",
  31. "updateTime": "2023-09-02 12:08:33"
  32. }
  33. ])
  34. //1.2 声明一个异步函数
  35. const articleCategoryList = async()=>{
  36. let result = await articleCategoryListService()
  37. categorys.value = result.data;
  38. }
  39. articleCategoryList();
  40. //6.1 控制添加分类弹窗
  41. const dialogVisible = ref(false)
  42. //6.1 添加分类数据模型
  43. const categoryModel = ref({
  44. categoryName: '',
  45. categoryAlias: ''
  46. })
  47. //6.1 添加分类表单校验
  48. const rules = {
  49. categoryName: [
  50. { required: true, message: '请输入分类名称', trigger: 'blur' },
  51. ],
  52. categoryAlias: [
  53. { required: true, message: '请输入分类别名', trigger: 'blur' },
  54. ]
  55. }
  56. //6.1 调用接口添加表单
  57. const addCategory = async ()=>{
  58. let result = await articleCategoryAddService(categoryModel.value);
  59. ElMessage.success(result.message? result.message:'添加成功')
  60. //隐藏弹窗
  61. dialogVisible.value = false
  62. //再次访问后台接口,查询所有分类
  63. articleCategoryList()
  64. }
  65. //7.1.1 弹窗标题
  66. const title=ref('')
  67. //7.2展示编辑弹窗
  68. const showDialog = (row)=>{
  69. title.value = '修改分类';dialogVisible.value = true
  70. //数据拷贝
  71. categoryModel.value.categoryName = row.categoryName;
  72. categoryModel.value.categoryAlias = row.categoryAlias;
  73. //扩展id属性,将来需要传参给后台完成分类的修改
  74. categoryModel.value.id = row.id
  75. }
  76. //7.3.3修改分类
  77. const updateCategory=async ()=>{
  78. let result = await articleCategoryUpdateService(categoryModel.value)
  79. ElMessage.success(result.message? result.message:'修改成功')
  80. //隐藏弹窗
  81. dialogVisible.value=false
  82. //再次访问后台接口,查询所有分类
  83. articleCategoryList()
  84. }
  85. //7.3.4 清空模型数据
  86. const clearCategoryModel = ()=>{
  87. categoryModel.value.categoryName='',
  88. categoryModel.value.categoryAlias=''
  89. }
  90. //8.2 删除分类 给删除按钮绑定事件
  91. const deleteCategory = (row) => {
  92. // 提示用户 确认框
  93. ElMessageBox.confirm(
  94. '你确认删除该分类信息吗?',
  95. '温馨提示',
  96. {
  97. confirmButtonText: '确认',
  98. cancelButtonText: '取消',
  99. type: 'warning',
  100. }
  101. )
  102. .then(async() => {
  103. //用户点击了确认
  104. let result = await articleCategoryDeleteService(row.id)
  105. // 给出提示
  106. ElMessage({
  107. type: 'success',
  108. message: '删除成功',
  109. })
  110. //刷新列表//再次访问后台接口,查询所有分类
  111. articleCategoryList()
  112. })
  113. .catch(() => {
  114. //用户点击了取消
  115. ElMessage({
  116. type: 'info',
  117. message: '取消删除',
  118. })
  119. })
  120. }
  121. </script>
  122. <template>
  123. <el-card class="page-container">
  124. <template #header>
  125. <div class="header">
  126. <span>文章分类</span>
  127. <div class="extra">
  128. <el-button type="primary" @click="title='添加分类';dialogVisible = true;clearCategoryModel()">添加分类</el-button> <!-- 六 6.1 @click="dialogVisible = true"绑定点击事件 六7.1.3 title='添加分类'; 六 7.3.4 清空模型数据 clearCategoryModel()-->
  129. </div>
  130. </div>
  131. </template>
  132. <el-table :data="categorys" style="width: 100%">
  133. <el-table-column label="序号" width="100" type="index"> </el-table-column>
  134. <el-table-column label="分类名称" prop="categoryName"></el-table-column>
  135. <el-table-column label="分类别名" prop="categoryAlias"></el-table-column>
  136. <el-table-column label="创建时间" prop="createTime"></el-table-column>
  137. <el-table-column label="更新时间" prop="updateTime"></el-table-column>
  138. <el-table-column label="操作" width="100">
  139. <template #default="{ row }">
  140. <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button> <!-- 六 7.1.4 @click="title='修改分类';dialogVisible=true"绑定事件 六 7.2 showDialog(row)-->
  141. <el-button :icon="Delete" circle plain type="danger" @click="deleteCategory(row)"></el-button> <!-- 六 8.3 @click="deleteCategory(row)" 绑定删除事件-->
  142. </template>
  143. </el-table-column>
  144. <template #empty>
  145. <el-empty description="没有数据" />
  146. </template>
  147. </el-table>
  148. <!-- 六 6.1 添加分类弹窗 -->
  149. <el-dialog v-model="dialogVisible" :title="title" width="30%"> <!-- 六 7.1.2 :title="title"绑定标题-->
  150. <el-form :model="categoryModel" :rules="rules" label-width="100px" style="padding-right: 30px">
  151. <el-form-item label="分类名称" prop="categoryName">
  152. <el-input v-model="categoryModel.categoryName" minlength="1" maxlength="10"></el-input>
  153. </el-form-item>
  154. <el-form-item label="分类别名" prop="categoryAlias">
  155. <el-input v-model="categoryModel.categoryAlias" minlength="1" maxlength="15"></el-input>
  156. </el-form-item>
  157. </el-form>
  158. <template #footer>
  159. <span class="dialog-footer">
  160. <el-button @click="dialogVisible = false">取消</el-button>
  161. <el-button type="primary" @click="title==='添加分类'? addCategory():updateCategory()"> 确认 </el-button> <!-- 六 6.1 @click="addCategory"绑定点击事件 六 7.3.1 @click="title==='添加分类'? addCategory():updateCategory()"-->
  162. </span>
  163. </template>
  164. </el-dialog>
  165. </el-card>
  166. </template>
  167. <style lang="scss" scoped>
  168. .page-container {
  169. min-height: 100%;
  170. box-sizing: border-box;
  171. .header {
  172. display: flex;
  173. align-items: center;
  174. justify-content: space-between;
  175. }
  176. }
  177. </style>

8.5 测试验证

七、文章列表 

1、 文章列表查询

 1.1 文章列表页面组件ArticleManage.vue

  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //文章分类数据模型
  8. const categorys = ref([
  9. {
  10. "id": 3,
  11. "categoryName": "美食",
  12. "categoryAlias": "my",
  13. "createTime": "2023-09-02 12:06:59",
  14. "updateTime": "2023-09-02 12:06:59"
  15. },
  16. {
  17. "id": 4,
  18. "categoryName": "娱乐",
  19. "categoryAlias": "yl",
  20. "createTime": "2023-09-02 12:08:16",
  21. "updateTime": "2023-09-02 12:08:16"
  22. },
  23. {
  24. "id": 5,
  25. "categoryName": "军事",
  26. "categoryAlias": "js",
  27. "createTime": "2023-09-02 12:08:33",
  28. "updateTime": "2023-09-02 12:08:33"
  29. }
  30. ])
  31. //用户搜索时选中的分类id
  32. const categoryId=ref('')
  33. //用户搜索时选中的发布状态
  34. const state=ref('')
  35. //文章列表数据模型
  36. const articles = ref([
  37. {
  38. "id": 5,
  39. "title": "陕西旅游攻略",
  40. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  41. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  42. "state": "草稿",
  43. "categoryId": 2,
  44. "createTime": "2023-09-03 11:55:30",
  45. "updateTime": "2023-09-03 11:55:30"
  46. },
  47. {
  48. "id": 5,
  49. "title": "陕西旅游攻略",
  50. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  51. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  52. "state": "草稿",
  53. "categoryId": 2,
  54. "createTime": "2023-09-03 11:55:30",
  55. "updateTime": "2023-09-03 11:55:30"
  56. },
  57. {
  58. "id": 5,
  59. "title": "陕西旅游攻略",
  60. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  61. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  62. "state": "草稿",
  63. "categoryId": 2,
  64. "createTime": "2023-09-03 11:55:30",
  65. "updateTime": "2023-09-03 11:55:30"
  66. },
  67. ])
  68. //分页条数据模型
  69. const pageNum = ref(1)//当前页
  70. const total = ref(20)//总条数
  71. const pageSize = ref(3)//每页条数
  72. //当每页条数发生了变化,调用此函数
  73. const onSizeChange = (size) => {
  74. pageSize.value = size
  75. }
  76. //当前页码发生变化,调用此函数
  77. const onCurrentChange = (num) => {
  78. pageNum.value = num
  79. }
  80. </script>
  81. <template>
  82. <el-card class="page-container">
  83. <template #header>
  84. <div class="header">
  85. <span>文章管理</span>
  86. <div class="extra">
  87. <el-button type="primary">添加文章</el-button>
  88. </div>
  89. </div>
  90. </template>
  91. <!-- 搜索表单 -->
  92. <el-form inline>
  93. <el-form-item label="文章分类:">
  94. <el-select placeholder="请选择" v-model="categoryId">
  95. <el-option
  96. v-for="c in categorys"
  97. :key="c.id"
  98. :label="c.categoryName"
  99. :value="c.id">
  100. </el-option>
  101. </el-select>
  102. </el-form-item>
  103. <el-form-item label="发布状态:">
  104. <el-select placeholder="请选择" v-model="state">
  105. <el-option label="已发布" value="已发布"></el-option>
  106. <el-option label="草稿" value="草稿"></el-option>
  107. </el-select>
  108. </el-form-item>
  109. <el-form-item>
  110. <el-button type="primary">搜索</el-button>
  111. <el-button>重置</el-button>
  112. </el-form-item>
  113. </el-form>
  114. <!-- 文章列表 -->
  115. <el-table :data="articles" style="width: 100%">
  116. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  117. <el-table-column label="分类" prop="categoryId"></el-table-column>
  118. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  119. <el-table-column label="状态" prop="state"></el-table-column>
  120. <el-table-column label="操作" width="100">
  121. <template #default="{ row }">
  122. <el-button :icon="Edit" circle plain type="primary"></el-button>
  123. <el-button :icon="Delete" circle plain type="danger"></el-button>
  124. </template>
  125. </el-table-column>
  126. <template #empty>
  127. <el-empty description="没有数据" />
  128. </template>
  129. </el-table>
  130. <!-- 分页条 -->
  131. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  132. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  133. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  134. </el-card>
  135. </template>
  136. <style lang="scss" scoped>
  137. .page-container {
  138. min-height: 100%;
  139. box-sizing: border-box;
  140. .header {
  141. display: flex;
  142. align-items: center;
  143. justify-content: space-between;
  144. }
  145. }
  146. </style>

1.2 解决分页控件英文显示问题main.js

  1. import './assets/main.scss' // 本项目使用sass
  2. import { createApp } from 'vue'
  3. import ElementPlus from 'element-plus'
  4. import 'element-plus/dist/index.css'
  5. //1.2 解决分页控件显示英文问题
  6. import locale from 'element-plus/dist/locale/zh-cn.js'
  7. //2.3
  8. import router from '@/router'
  9. import App from './App.vue'
  10. //2.2
  11. import {createPinia} from 'pinia'
  12. //4.2 导入持久化插件
  13. import {createPersistedState} from 'pinia-persistedstate-plugin'
  14. const app = createApp(App)
  15. //2.2
  16. const pinia = createPinia();
  17. //4.2
  18. const persist = createPersistedState()
  19. //4.2 pinia使用持久化插件
  20. pinia.use(persist)
  21. app.use(pinia)
  22. //2.3
  23. app.use(router)
  24. //1.2 解决分页控件显示英文问题
  25. app.use(ElementPlus,{locale})
  26. app.mount('#app')

1.3 文章分类数据回显ArticleMange.vue  

  1. //文章列表查询
  2. import { articleCategoryListService } from '@/api/article.js'
  3. const getArticleCategoryList = async () => {
  4.     //获取所有分类
  5.     let resultC = await articleCategoryListService();
  6.     categorys.value = resultC.data
  7. }
  8. getArticleCategoryList(); 

1.4 文章列表接口调用

1.4.1 article.js中提供获取文章列表数据的函数
  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
  22. //8.1 删除分类
  23. export const articleCategoryDeleteService = (id) => {
  24. return request.delete('/category?id='+id)
  25. }
  26. //1.4.1 文章列表查询
  27. export const articleListService = (params) => {
  28. return request.get('/article', { params: params })
  29. }
1.4.2 ArticleManage.vue中,调用接口获取数据
  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 八 1.4.2 articleListService
  8. import { articleCategoryListService ,articleListService} from '@/api/article.js'
  9. //文章分类数据模型
  10. const categorys = ref([
  11. {
  12. "id": 3,
  13. "categoryName": "美食",
  14. "categoryAlias": "my",
  15. "createTime": "2023-09-02 12:06:59",
  16. "updateTime": "2023-09-02 12:06:59"
  17. },
  18. {
  19. "id": 4,
  20. "categoryName": "娱乐",
  21. "categoryAlias": "yl",
  22. "createTime": "2023-09-02 12:08:16",
  23. "updateTime": "2023-09-02 12:08:16"
  24. },
  25. {
  26. "id": 5,
  27. "categoryName": "军事",
  28. "categoryAlias": "js",
  29. "createTime": "2023-09-02 12:08:33",
  30. "updateTime": "2023-09-02 12:08:33"
  31. }
  32. ])
  33. //用户搜索时选中的分类id
  34. const categoryId=ref('')
  35. //用户搜索时选中的发布状态
  36. const state=ref('')
  37. //文章列表数据模型
  38. const articles = ref([
  39. {
  40. "id": 5,
  41. "title": "陕西旅游攻略",
  42. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  43. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  44. "state": "草稿",
  45. "categoryId": 2,
  46. "createTime": "2023-09-03 11:55:30",
  47. "updateTime": "2023-09-03 11:55:30"
  48. },
  49. {
  50. "id": 5,
  51. "title": "陕西旅游攻略",
  52. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  53. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  54. "state": "草稿",
  55. "categoryId": 2,
  56. "createTime": "2023-09-03 11:55:30",
  57. "updateTime": "2023-09-03 11:55:30"
  58. },
  59. {
  60. "id": 5,
  61. "title": "陕西旅游攻略",
  62. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  63. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  64. "state": "已发布",
  65. "categoryId": 2,
  66. "createTime": "2023-09-03 11:55:30",
  67. "updateTime": "2023-09-03 11:55:30"
  68. },
  69. ])
  70. //分页条数据模型
  71. const pageNum = ref(1)//当前页
  72. const total = ref(20)//总条数
  73. const pageSize = ref(3)//每页条数
  74. //当每页条数发生了变化,调用此函数
  75. const onSizeChange = (size) => {
  76. pageSize.value = size
  77. }
  78. //当前页码发生变化,调用此函数
  79. const onCurrentChange = (num) => {
  80. pageNum.value = num
  81. }
  82. //1.3 搜索查询条件 文章列表查询
  83. const getArticleCategoryList = async () => {
  84. //获取所有分类
  85. let resultC = await articleCategoryListService();
  86. categorys.value = resultC.data
  87. }
  88. //1.4.2 获取文章列表数据
  89. const articleList = async () => {
  90. let params = {
  91. pageNum: pageNum.value,
  92. pageSize: pageSize.value,
  93. categoryId: categoryId.value ? categoryId.value : null,
  94. state: state.value ? state.value : null
  95. }
  96. let result = await articleListService(params);
  97. //渲染视图
  98. total.value = result.data.total;
  99. articles.value = result.data.items;
  100. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  101. for (let i = 0; i < articles.value.length; i++) {
  102. let article = articles.value[i];
  103. for (let j = 0; j < categorys.value.length; j++) {
  104. if (article.categoryId == categorys.value[j].id) {
  105. article.categoryName = categorys.value[j].categoryName;
  106. }
  107. }
  108. }
  109. }
  110. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  111. getArticleCategoryList();
  112. //1.4.2 获取文章列表数据
  113. articleList();
  114. </script>
  115. <template>
  116. <el-card class="page-container">
  117. <!-- 1 标题 -->
  118. <template #header>
  119. <div class="header">
  120. <span>文章管理</span>
  121. <div class="extra">
  122. <el-button type="primary">添加文章</el-button>
  123. </div>
  124. </div>
  125. </template>
  126. <!-- 2 搜索表单 -->
  127. <el-form inline>
  128. <el-form-item label="文章分类:">
  129. <el-select placeholder="请选择" v-model="categoryId">
  130. <el-option
  131. v-for="c in categorys"
  132. :key="c.id"
  133. :label="c.categoryName"
  134. :value="c.id">
  135. </el-option>
  136. </el-select>
  137. </el-form-item>
  138. <el-form-item label="发布状态:">
  139. <el-select placeholder="请选择" v-model="state">
  140. <el-option label="已发布" value="已发布"></el-option>
  141. <el-option label="草稿" value="草稿"></el-option>
  142. </el-select>
  143. </el-form-item>
  144. <el-form-item>
  145. <el-button type="primary">搜索</el-button>
  146. <el-button>重置</el-button>
  147. </el-form-item>
  148. </el-form>
  149. <!-- 3 文章列表 -->
  150. <el-table :data="articles" style="width: 100%">
  151. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  152. <el-table-column label="分类" prop="categoryName"></el-table-column>
  153. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  154. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  155. <el-table-column label="状态" prop="state"></el-table-column>
  156. <el-table-column label="操作" width="100">
  157. <template #default="{ row }">
  158. <el-button :icon="Edit" circle plain type="primary"></el-button>
  159. <el-button :icon="Delete" circle plain type="danger"></el-button>
  160. </template>
  161. </el-table-column>
  162. <template #empty>
  163. <el-empty description="没有数据" />
  164. </template>
  165. </el-table>
  166. <!-- 4 分页条 -->
  167. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  168. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  169. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  170. </el-card>
  171. </template>
  172. <style lang="scss" scoped>
  173. .page-container {
  174. min-height: 100%;
  175. box-sizing: border-box;
  176. .header {
  177. display: flex;
  178. align-items: center;
  179. justify-content: space-between;
  180. }
  181. }
  182. </style>

 

1.4.3 当分页条的当前页和每页条数发生变化,重新发送请求获取数据
  1. //当每页条数发生了变化,调用此函数
  2. const onSizeChange = (size) => {
  3. pageSize.value = size
  4. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  5. }
  6. //当前页码发生变化,调用此函数
  7. const onCurrentChange = (num) => {
  8. pageNum.value = num
  9. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  10. }

2 、搜索和重置

为搜索按钮绑定单击事件,调用getArticles函数即可

为重置按钮绑定单击事件,清除categoryId和state的之即可

  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 八 1.4.2 articleListService
  8. import { articleCategoryListService ,articleListService} from '@/api/article.js'
  9. //文章分类数据模型
  10. const categorys = ref([
  11. {
  12. "id": 3,
  13. "categoryName": "美食",
  14. "categoryAlias": "my",
  15. "createTime": "2023-09-02 12:06:59",
  16. "updateTime": "2023-09-02 12:06:59"
  17. },
  18. {
  19. "id": 4,
  20. "categoryName": "娱乐",
  21. "categoryAlias": "yl",
  22. "createTime": "2023-09-02 12:08:16",
  23. "updateTime": "2023-09-02 12:08:16"
  24. },
  25. {
  26. "id": 5,
  27. "categoryName": "军事",
  28. "categoryAlias": "js",
  29. "createTime": "2023-09-02 12:08:33",
  30. "updateTime": "2023-09-02 12:08:33"
  31. }
  32. ])
  33. //用户搜索时选中的分类id
  34. const categoryId=ref('')
  35. //用户搜索时选中的发布状态
  36. const state=ref('')
  37. //文章列表数据模型
  38. const articles = ref([
  39. {
  40. "id": 5,
  41. "title": "陕西旅游攻略",
  42. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  43. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  44. "state": "草稿",
  45. "categoryId": 2,
  46. "createTime": "2023-09-03 11:55:30",
  47. "updateTime": "2023-09-03 11:55:30"
  48. },
  49. {
  50. "id": 5,
  51. "title": "陕西旅游攻略",
  52. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  53. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  54. "state": "草稿",
  55. "categoryId": 2,
  56. "createTime": "2023-09-03 11:55:30",
  57. "updateTime": "2023-09-03 11:55:30"
  58. },
  59. {
  60. "id": 5,
  61. "title": "陕西旅游攻略",
  62. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  63. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  64. "state": "已发布",
  65. "categoryId": 2,
  66. "createTime": "2023-09-03 11:55:30",
  67. "updateTime": "2023-09-03 11:55:30"
  68. },
  69. ])
  70. //分页条数据模型
  71. const pageNum = ref(1)//当前页
  72. const total = ref(20)//总条数
  73. const pageSize = ref(3)//每页条数
  74. //当每页条数发生了变化,调用此函数
  75. const onSizeChange = (size) => {
  76. pageSize.value = size
  77. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  78. }
  79. //当前页码发生变化,调用此函数
  80. const onCurrentChange = (num) => {
  81. pageNum.value = num
  82. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  83. }
  84. //1.3 搜索查询条件 文章列表查询
  85. const getArticleCategoryList = async () => {
  86. //获取所有分类
  87. let resultC = await articleCategoryListService();
  88. categorys.value = resultC.data
  89. }
  90. //1.4.2 获取文章列表数据
  91. const articleList = async () => {
  92. let params = {
  93. pageNum: pageNum.value,
  94. pageSize: pageSize.value,
  95. categoryId: categoryId.value ? categoryId.value : null,
  96. state: state.value ? state.value : null
  97. }
  98. let result = await articleListService(params);
  99. //渲染视图
  100. total.value = result.data.total;
  101. articles.value = result.data.items;
  102. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  103. for (let i = 0; i < articles.value.length; i++) {
  104. let article = articles.value[i];
  105. for (let j = 0; j < categorys.value.length; j++) {
  106. if (article.categoryId == categorys.value[j].id) {
  107. article.categoryName = categorys.value[j].categoryName;
  108. }
  109. }
  110. }
  111. }
  112. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  113. getArticleCategoryList();
  114. //1.4.2 获取文章列表数据
  115. articleList();
  116. </script>
  117. <template>
  118. <el-card class="page-container">
  119. <!-- 1 标题 -->
  120. <template #header>
  121. <div class="header">
  122. <span>文章管理</span>
  123. <div class="extra">
  124. <el-button type="primary">添加文章</el-button>
  125. </div>
  126. </div>
  127. </template>
  128. <!-- 2 搜索表单 -->
  129. <el-form inline>
  130. <el-form-item label="文章分类:">
  131. <el-select placeholder="请选择" v-model="categoryId">
  132. <el-option
  133. v-for="c in categorys"
  134. :key="c.id"
  135. :label="c.categoryName"
  136. :value="c.id">
  137. </el-option>
  138. </el-select>
  139. </el-form-item>
  140. <el-form-item label="发布状态:">
  141. <el-select placeholder="请选择" v-model="state">
  142. <el-option label="已发布" value="已发布"></el-option>
  143. <el-option label="草稿" value="草稿"></el-option>
  144. </el-select>
  145. </el-form-item>
  146. <el-form-item>
  147. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  148. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  149. </el-form-item>
  150. </el-form>
  151. <!-- 3 文章列表 -->
  152. <el-table :data="articles" style="width: 100%">
  153. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  154. <el-table-column label="分类" prop="categoryName"></el-table-column>
  155. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  156. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  157. <el-table-column label="状态" prop="state"></el-table-column>
  158. <el-table-column label="操作" width="100">
  159. <template #default="{ row }">
  160. <el-button :icon="Edit" circle plain type="primary"></el-button>
  161. <el-button :icon="Delete" circle plain type="danger"></el-button>
  162. </template>
  163. </el-table-column>
  164. <template #empty>
  165. <el-empty description="没有数据" />
  166. </template>
  167. </el-table>
  168. <!-- 4 分页条 -->
  169. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  170. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  171. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  172. </el-card>
  173. </template>
  174. <style lang="scss" scoped>
  175. .page-container {
  176. min-height: 100%;
  177. box-sizing: border-box;
  178. .header {
  179. display: flex;
  180. align-items: center;
  181. justify-content: space-between;
  182. }
  183. }
  184. </style>

3、添加文章

3.1 添加文章抽屉组件

  1. import {Plus} from '@element-plus/icons-vue'
  2. //控制抽屉是否显示
  3. const visibleDrawer = ref(false)
  4. //添加表单数据模型
  5. const articleModel = ref({
  6. title: '',
  7. categoryId: '',
  8. coverImg: '',
  9. content:'',
  10. sta
  1. <!-- 抽屉 -->
  2. <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
  3. <!-- 添加文章表单 -->
  4. <el-form :model="articleModel" label-width="100px" >
  5. <el-form-item label="文章标题" >
  6. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  7. </el-form-item>
  8. <el-form-item label="文章分类">
  9. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  10. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  11. </el-option>
  12. </el-select>
  13. </el-form-item>
  14. <el-form-item label="文章封面">
  15. <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false">
  16. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  17. <el-icon v-else class="avatar-uploader-icon">
  18. <Plus />
  19. </el-icon>
  20. </el-upload>
  21. </el-form-item>
  22. <el-form-item label="文章内容">
  23. <div class="editor">富文本编辑器</div>
  24. </el-form-item>
  25. <el-form-item>
  26. <el-button type="primary">发布</el-button>
  27. <el-button type="info">草稿</el-button>
  28. </el-form-item>
  29. </el-form>
  30. </el-drawer>

  1. /* 抽屉样式 */
  2. .avatar-uploader {
  3. :deep() {
  4. .avatar {
  5. width: 178px;
  6. height: 178px;
  7. display: block;
  8. }
  9. .el-upload {
  10. border: 1px dashed var(--el-border-color);
  11. border-radius: 6px;
  12. cursor: pointer;
  13. position: relative;
  14. overflow: hidden;
  15. transition: var(--el-transition-duration-fast);
  16. }
  17. .el-upload:hover {
  18. border-color: var(--el-color-primary);
  19. }
  20. .el-icon.avatar-uploader-icon {
  21. font-size: 28px;
  22. color: #8c939d;
  23. width: 178px;
  24. height: 178px;
  25. text-align: center;
  26. }
  27. }
  28. }
  29. .editor {
  30. width: 100%;
  31. :deep(.ql-editor) {
  32. min-height: 200px;
  33. }
  34. }

3.2 为添加文章按钮添加单击事件,展示抽屉

  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 八 1.4.2 articleListService
  8. import { articleCategoryListService ,articleListService} from '@/api/article.js'
  9. //3.1 导入添加抽屉组件
  10. import {Plus} from '@element-plus/icons-vue'
  11. //3.1 控制抽屉是否显示
  12. const visibleDrawer = ref(false)
  13. //3.1 添加表单数据模型
  14. const articleModel = ref({
  15. title: '',
  16. categoryId: '',
  17. coverImg: '',
  18. content:'',
  19. state:''
  20. })
  21. //文章分类数据模型
  22. const categorys = ref([
  23. {
  24. "id": 3,
  25. "categoryName": "美食",
  26. "categoryAlias": "my",
  27. "createTime": "2023-09-02 12:06:59",
  28. "updateTime": "2023-09-02 12:06:59"
  29. },
  30. {
  31. "id": 4,
  32. "categoryName": "娱乐",
  33. "categoryAlias": "yl",
  34. "createTime": "2023-09-02 12:08:16",
  35. "updateTime": "2023-09-02 12:08:16"
  36. },
  37. {
  38. "id": 5,
  39. "categoryName": "军事",
  40. "categoryAlias": "js",
  41. "createTime": "2023-09-02 12:08:33",
  42. "updateTime": "2023-09-02 12:08:33"
  43. }
  44. ])
  45. //用户搜索时选中的分类id
  46. const categoryId=ref('')
  47. //用户搜索时选中的发布状态
  48. const state=ref('')
  49. //文章列表数据模型
  50. const articles = ref([
  51. {
  52. "id": 5,
  53. "title": "陕西旅游攻略",
  54. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  55. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  56. "state": "草稿",
  57. "categoryId": 2,
  58. "createTime": "2023-09-03 11:55:30",
  59. "updateTime": "2023-09-03 11:55:30"
  60. },
  61. {
  62. "id": 5,
  63. "title": "陕西旅游攻略",
  64. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  65. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  66. "state": "草稿",
  67. "categoryId": 2,
  68. "createTime": "2023-09-03 11:55:30",
  69. "updateTime": "2023-09-03 11:55:30"
  70. },
  71. {
  72. "id": 5,
  73. "title": "陕西旅游攻略",
  74. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  75. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  76. "state": "已发布",
  77. "categoryId": 2,
  78. "createTime": "2023-09-03 11:55:30",
  79. "updateTime": "2023-09-03 11:55:30"
  80. },
  81. ])
  82. //分页条数据模型
  83. const pageNum = ref(1)//当前页
  84. const total = ref(20)//总条数
  85. const pageSize = ref(3)//每页条数
  86. //当每页条数发生了变化,调用此函数
  87. const onSizeChange = (size) => {
  88. pageSize.value = size
  89. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  90. }
  91. //当前页码发生变化,调用此函数
  92. const onCurrentChange = (num) => {
  93. pageNum.value = num
  94. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  95. }
  96. //1.3 搜索查询条件 文章列表查询
  97. const getArticleCategoryList = async () => {
  98. //获取所有分类
  99. let resultC = await articleCategoryListService();
  100. categorys.value = resultC.data
  101. }
  102. //1.4.2 获取文章列表数据
  103. const articleList = async () => {
  104. let params = {
  105. pageNum: pageNum.value,
  106. pageSize: pageSize.value,
  107. categoryId: categoryId.value ? categoryId.value : null,
  108. state: state.value ? state.value : null
  109. }
  110. let result = await articleListService(params);
  111. //渲染视图
  112. total.value = result.data.total;
  113. articles.value = result.data.items;
  114. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  115. for (let i = 0; i < articles.value.length; i++) {
  116. let article = articles.value[i];
  117. for (let j = 0; j < categorys.value.length; j++) {
  118. if (article.categoryId == categorys.value[j].id) {
  119. article.categoryName = categorys.value[j].categoryName;
  120. }
  121. }
  122. }
  123. }
  124. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  125. getArticleCategoryList();
  126. //1.4.2 获取文章列表数据
  127. articleList();
  128. </script>
  129. <template>
  130. <el-card class="page-container">
  131. <!-- 1 标题 -->
  132. <template #header>
  133. <div class="header">
  134. <span>文章管理</span>
  135. <div class="extra">
  136. <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件-->
  137. </div>
  138. </div>
  139. </template>
  140. <!-- 2 搜索表单 -->
  141. <el-form inline>
  142. <el-form-item label="文章分类:">
  143. <el-select placeholder="请选择" v-model="categoryId">
  144. <el-option
  145. v-for="c in categorys"
  146. :key="c.id"
  147. :label="c.categoryName"
  148. :value="c.id">
  149. </el-option>
  150. </el-select>
  151. </el-form-item>
  152. <el-form-item label="发布状态:">
  153. <el-select placeholder="请选择" v-model="state">
  154. <el-option label="已发布" value="已发布"></el-option>
  155. <el-option label="草稿" value="草稿"></el-option>
  156. </el-select>
  157. </el-form-item>
  158. <el-form-item>
  159. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  160. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  161. </el-form-item>
  162. </el-form>
  163. <!-- 3 文章列表 -->
  164. <el-table :data="articles" style="width: 100%">
  165. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  166. <el-table-column label="分类" prop="categoryName"></el-table-column>
  167. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  168. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  169. <el-table-column label="状态" prop="state"></el-table-column>
  170. <el-table-column label="操作" width="100">
  171. <template #default="{ row }">
  172. <el-button :icon="Edit" circle plain type="primary"></el-button>
  173. <el-button :icon="Delete" circle plain type="danger"></el-button>
  174. </template>
  175. </el-table-column>
  176. <template #empty>
  177. <el-empty description="没有数据" />
  178. </template>
  179. </el-table>
  180. <!-- 4 分页条 -->
  181. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  182. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  183. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  184. <!-- 七 3.1 抽屉 -->
  185. <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
  186. <!-- 添加文章表单 -->
  187. <el-form :model="articleModel" label-width="100px" >
  188. <el-form-item label="文章标题" >
  189. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  190. </el-form-item>
  191. <el-form-item label="文章分类">
  192. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  193. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  194. </el-option>
  195. </el-select>
  196. </el-form-item>
  197. <el-form-item label="文章封面">
  198. <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false">
  199. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  200. <el-icon v-else class="avatar-uploader-icon">
  201. <Plus />
  202. </el-icon>
  203. </el-upload>
  204. </el-form-item>
  205. <el-form-item label="文章内容">
  206. <div class="editor">富文本编辑器</div>
  207. </el-form-item>
  208. <el-form-item>
  209. <el-button type="primary">发布</el-button>
  210. <el-button type="info">草稿</el-button>
  211. </el-form-item>
  212. </el-form>
  213. </el-drawer>
  214. </el-card>
  215. </template>
  216. <style lang="scss" scoped>
  217. .page-container {
  218. min-height: 100%;
  219. box-sizing: border-box;
  220. .header {
  221. display: flex;
  222. align-items: center;
  223. justify-content: space-between;
  224. }
  225. }
  226. /*3.1 抽屉样式 */
  227. .avatar-uploader {
  228. :deep() {
  229. .avatar {
  230. width: 178px;
  231. height: 178px;
  232. display: block;
  233. }
  234. .el-upload {
  235. border: 1px dashed var(--el-border-color);
  236. border-radius: 6px;
  237. cursor: pointer;
  238. position: relative;
  239. overflow: hidden;
  240. transition: var(--el-transition-duration-fast);
  241. }
  242. .el-upload:hover {
  243. border-color: var(--el-color-primary);
  244. }
  245. .el-icon.avatar-uploader-icon {
  246. font-size: 28px;
  247. color: #8c939d;
  248. width: 178px;
  249. height: 178px;
  250. text-align: center;
  251. }
  252. }
  253. }
  254. .editor {
  255. width: 100%;
  256. :deep(.ql-editor) {
  257. min-height: 200px;
  258. }
  259. }
  260. </style>

3.3 富文本编辑器

文章内容需要使用到富文本编辑器,这里咱们使用一个开源的富文本编辑器 Quill

官网地址: VueQuill | Rich Text Editor Component for Vue 3

3.3.1 安装:
npm install @vueup/vue-quill@latest --save

3.3.2 导入组件和样式:
  1. import { QuillEditor } from '@vueup/vue-quill'
  2. import '@vueup/vue-quill/dist/vue-quill.snow.css'
3.3.3 页面使用quill组件:
  1. <quill-editor
  2.              theme="snow"
  3.              v-model:content="articleModel.content"
  4.              contentType="html"
  5.              >
  6. </quill-editor>
3.3.4 样式美化:
  1. .editor {
  2.  width: 100%;
  3. :deep(.ql-editor) {
  4.    min-height: 200px;
  5. }
  6. }
  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 八 1.4.2 articleListService
  8. import { articleCategoryListService ,articleListService} from '@/api/article.js'
  9. //3.1 导入添加抽屉组件
  10. import {Plus} from '@element-plus/icons-vue'
  11. //3.3.2 导入组件和样式
  12. import { QuillEditor } from '@vueup/vue-quill'
  13. import '@vueup/vue-quill/dist/vue-quill.snow.css'
  14. //3.1 控制抽屉是否显示
  15. const visibleDrawer = ref(false)
  16. //3.1 添加表单数据模型
  17. const articleModel = ref({
  18. title: '',
  19. categoryId: '',
  20. coverImg: '',
  21. content:'',
  22. state:''
  23. })
  24. //文章分类数据模型
  25. const categorys = ref([
  26. {
  27. "id": 3,
  28. "categoryName": "美食",
  29. "categoryAlias": "my",
  30. "createTime": "2023-09-02 12:06:59",
  31. "updateTime": "2023-09-02 12:06:59"
  32. },
  33. {
  34. "id": 4,
  35. "categoryName": "娱乐",
  36. "categoryAlias": "yl",
  37. "createTime": "2023-09-02 12:08:16",
  38. "updateTime": "2023-09-02 12:08:16"
  39. },
  40. {
  41. "id": 5,
  42. "categoryName": "军事",
  43. "categoryAlias": "js",
  44. "createTime": "2023-09-02 12:08:33",
  45. "updateTime": "2023-09-02 12:08:33"
  46. }
  47. ])
  48. //用户搜索时选中的分类id
  49. const categoryId=ref('')
  50. //用户搜索时选中的发布状态
  51. const state=ref('')
  52. //文章列表数据模型
  53. const articles = ref([
  54. {
  55. "id": 5,
  56. "title": "陕西旅游攻略",
  57. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  58. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  59. "state": "草稿",
  60. "categoryId": 2,
  61. "createTime": "2023-09-03 11:55:30",
  62. "updateTime": "2023-09-03 11:55:30"
  63. },
  64. {
  65. "id": 5,
  66. "title": "陕西旅游攻略",
  67. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  68. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  69. "state": "草稿",
  70. "categoryId": 2,
  71. "createTime": "2023-09-03 11:55:30",
  72. "updateTime": "2023-09-03 11:55:30"
  73. },
  74. {
  75. "id": 5,
  76. "title": "陕西旅游攻略",
  77. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  78. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  79. "state": "已发布",
  80. "categoryId": 2,
  81. "createTime": "2023-09-03 11:55:30",
  82. "updateTime": "2023-09-03 11:55:30"
  83. },
  84. ])
  85. //分页条数据模型
  86. const pageNum = ref(1)//当前页
  87. const total = ref(20)//总条数
  88. const pageSize = ref(3)//每页条数
  89. //当每页条数发生了变化,调用此函数
  90. const onSizeChange = (size) => {
  91. pageSize.value = size
  92. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  93. }
  94. //当前页码发生变化,调用此函数
  95. const onCurrentChange = (num) => {
  96. pageNum.value = num
  97. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  98. }
  99. //1.3 搜索查询条件 文章列表查询
  100. const getArticleCategoryList = async () => {
  101. //获取所有分类
  102. let resultC = await articleCategoryListService();
  103. categorys.value = resultC.data
  104. }
  105. //1.4.2 获取文章列表数据
  106. const articleList = async () => {
  107. let params = {
  108. pageNum: pageNum.value,
  109. pageSize: pageSize.value,
  110. categoryId: categoryId.value ? categoryId.value : null,
  111. state: state.value ? state.value : null
  112. }
  113. let result = await articleListService(params);
  114. //渲染视图
  115. total.value = result.data.total;
  116. articles.value = result.data.items;
  117. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  118. for (let i = 0; i < articles.value.length; i++) {
  119. let article = articles.value[i];
  120. for (let j = 0; j < categorys.value.length; j++) {
  121. if (article.categoryId == categorys.value[j].id) {
  122. article.categoryName = categorys.value[j].categoryName;
  123. }
  124. }
  125. }
  126. }
  127. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  128. getArticleCategoryList();
  129. //1.4.2 获取文章列表数据
  130. articleList();
  131. </script>
  132. <template>
  133. <el-card class="page-container">
  134. <!-- 1 标题 -->
  135. <template #header>
  136. <div class="header">
  137. <span>文章管理</span>
  138. <div class="extra">
  139. <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件-->
  140. </div>
  141. </div>
  142. </template>
  143. <!-- 2 搜索表单 -->
  144. <el-form inline>
  145. <el-form-item label="文章分类:">
  146. <el-select placeholder="请选择" v-model="categoryId">
  147. <el-option
  148. v-for="c in categorys"
  149. :key="c.id"
  150. :label="c.categoryName"
  151. :value="c.id">
  152. </el-option>
  153. </el-select>
  154. </el-form-item>
  155. <el-form-item label="发布状态:">
  156. <el-select placeholder="请选择" v-model="state">
  157. <el-option label="已发布" value="已发布"></el-option>
  158. <el-option label="草稿" value="草稿"></el-option>
  159. </el-select>
  160. </el-form-item>
  161. <el-form-item>
  162. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  163. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  164. </el-form-item>
  165. </el-form>
  166. <!-- 3 文章列表 -->
  167. <el-table :data="articles" style="width: 100%">
  168. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  169. <el-table-column label="分类" prop="categoryName"></el-table-column>
  170. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  171. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  172. <el-table-column label="状态" prop="state"></el-table-column>
  173. <el-table-column label="操作" width="100">
  174. <template #default="{ row }">
  175. <el-button :icon="Edit" circle plain type="primary"></el-button>
  176. <el-button :icon="Delete" circle plain type="danger"></el-button>
  177. </template>
  178. </el-table-column>
  179. <template #empty>
  180. <el-empty description="没有数据" />
  181. </template>
  182. </el-table>
  183. <!-- 4 分页条 -->
  184. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  185. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  186. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  187. <!-- 七 3.1 抽屉 -->
  188. <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
  189. <!-- 添加文章表单 -->
  190. <el-form :model="articleModel" label-width="100px" >
  191. <el-form-item label="文章标题" >
  192. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  193. </el-form-item>
  194. <el-form-item label="文章分类">
  195. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  196. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  197. </el-option>
  198. </el-select>
  199. </el-form-item>
  200. <el-form-item label="文章封面">
  201. <el-upload class="avatar-uploader" :auto-upload="false" :show-file-list="false">
  202. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  203. <el-icon v-else class="avatar-uploader-icon">
  204. <Plus />
  205. </el-icon>
  206. </el-upload>
  207. </el-form-item>
  208. <el-form-item label="文章内容">
  209. <div class="editor">
  210. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
  211. </quill-editor>
  212. </div>
  213. </el-form-item>
  214. <el-form-item>
  215. <el-button type="primary">发布</el-button>
  216. <el-button type="info">草稿</el-button>
  217. </el-form-item>
  218. </el-form>
  219. </el-drawer>
  220. </el-card>
  221. </template>
  222. <style lang="scss" scoped>
  223. .page-container {
  224. min-height: 100%;
  225. box-sizing: border-box;
  226. .header {
  227. display: flex;
  228. align-items: center;
  229. justify-content: space-between;
  230. }
  231. }
  232. /*3.1 抽屉样式 */
  233. .avatar-uploader {
  234. :deep() {
  235. .avatar {
  236. width: 178px;
  237. height: 178px;
  238. display: block;
  239. }
  240. .el-upload {
  241. border: 1px dashed var(--el-border-color);
  242. border-radius: 6px;
  243. cursor: pointer;
  244. position: relative;
  245. overflow: hidden;
  246. transition: var(--el-transition-duration-fast);
  247. }
  248. .el-upload:hover {
  249. border-color: var(--el-color-primary);
  250. }
  251. .el-icon.avatar-uploader-icon {
  252. font-size: 28px;
  253. color: #8c939d;
  254. width: 178px;
  255. height: 178px;
  256. text-align: center;
  257. }
  258. }
  259. }
  260. .editor {
  261. width: 100%;
  262. :deep(.ql-editor) {
  263. min-height: 200px;
  264. }
  265. }
  266. //3.3.4 样式
  267. .editor {
  268. width: 100%;
  269. :deep(.ql-editor) {
  270. min-height: 200px;
  271. }
  272. }
  273. </style>

3.4 文章封面图片上传

将来当点击+图标,选择本地图片后,el-upload这个组件会自动发送请求,把图片上传到指定的服务器上,而不需要我们自己使用axios发送异步请求,所以需要给el-upload标签添加一些属性,控制请求的发送

auto-upload:是否自动上传

action: 服务器接口路径

name: 上传的文件字段名

headers: 设置上传的请求头

on-success: 上传成功的回调函数

  1. </el-form-item>
  2. <el-form-item label="文章封面">
  3. <!--
  4. auto-upload:是否自动上传
  5. action: 服务器接口路径
  6. name: 上传的文件字段名
  7. headers: 设置上传的请求头
  8. on-success: 上传成功的回调函数 -->
  9. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
  10. action="/api/upload"
  11. name="file"
  12. :headers="{Authorization:tokenStore.token}"
  13. :on-success="uploadSuccess"
  14. >
  15. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  16. <el-icon v-else class="avatar-uploader-icon">
  17. <Plus />
  18. </el-icon>
  19. </el-upload>
  20. </el-form-item>

注意:

  1. 由于这个请求时el-upload自动发送的异步请求,并没有使用咱们的request.js请求工具,所以在请求的路ing上,需要加上/api, 这个时候请求代理才能拦截到这个请求,转发到后台服务器上

  2. 要携带请求头,还需要导入pinia状态才可以使用

    1. import { useTokenStore } from '@/stores/token.js'
    2. const tokenStore = useTokenStore();
    1. <script setup>
    2. import {
    3. Edit,
    4. Delete
    5. } from '@element-plus/icons-vue'
    6. import { ref } from 'vue'
    7. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 八 1.4.2 articleListService
    8. import { articleCategoryListService ,articleListService} from '@/api/article.js'
    9. //3.1 导入添加抽屉组件
    10. import {Plus} from '@element-plus/icons-vue'
    11. //3.3.2 导入组件和样式
    12. import { QuillEditor } from '@vueup/vue-quill'
    13. import '@vueup/vue-quill/dist/vue-quill.snow.css'
    14. //3.4 文章封面上传 导入token
    15. import { useTokenStore } from '@/stores/token.js'
    16. const tokenStore = useTokenStore();
    17. //3.4 上传图片成功回调
    18. const uploadSuccess = (img) => {
    19. //img就是后台响应的数据,格式为:{code:状态码,message:提示信息,data: 图片的存储地址}
    20. articleModel.value.coverImg=img.data
    21. }
    22. //3.1 控制抽屉是否显示
    23. const visibleDrawer = ref(false)
    24. //3.1 添加表单数据模型
    25. const articleModel = ref({
    26. title: '',
    27. categoryId: '',
    28. coverImg: '',
    29. content:'',
    30. state:''
    31. })
    32. //文章分类数据模型
    33. const categorys = ref([
    34. {
    35. "id": 3,
    36. "categoryName": "美食",
    37. "categoryAlias": "my",
    38. "createTime": "2023-09-02 12:06:59",
    39. "updateTime": "2023-09-02 12:06:59"
    40. },
    41. {
    42. "id": 4,
    43. "categoryName": "娱乐",
    44. "categoryAlias": "yl",
    45. "createTime": "2023-09-02 12:08:16",
    46. "updateTime": "2023-09-02 12:08:16"
    47. },
    48. {
    49. "id": 5,
    50. "categoryName": "军事",
    51. "categoryAlias": "js",
    52. "createTime": "2023-09-02 12:08:33",
    53. "updateTime": "2023-09-02 12:08:33"
    54. }
    55. ])
    56. //用户搜索时选中的分类id
    57. const categoryId=ref('')
    58. //用户搜索时选中的发布状态
    59. const state=ref('')
    60. //文章列表数据模型
    61. const articles = ref([
    62. {
    63. "id": 5,
    64. "title": "陕西旅游攻略",
    65. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    66. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    67. "state": "草稿",
    68. "categoryId": 2,
    69. "createTime": "2023-09-03 11:55:30",
    70. "updateTime": "2023-09-03 11:55:30"
    71. },
    72. {
    73. "id": 5,
    74. "title": "陕西旅游攻略",
    75. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    76. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    77. "state": "草稿",
    78. "categoryId": 2,
    79. "createTime": "2023-09-03 11:55:30",
    80. "updateTime": "2023-09-03 11:55:30"
    81. },
    82. {
    83. "id": 5,
    84. "title": "陕西旅游攻略",
    85. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    86. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    87. "state": "已发布",
    88. "categoryId": 2,
    89. "createTime": "2023-09-03 11:55:30",
    90. "updateTime": "2023-09-03 11:55:30"
    91. },
    92. ])
    93. //分页条数据模型
    94. const pageNum = ref(1)//当前页
    95. const total = ref(20)//总条数
    96. const pageSize = ref(3)//每页条数
    97. //当每页条数发生了变化,调用此函数
    98. const onSizeChange = (size) => {
    99. pageSize.value = size
    100. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
    101. }
    102. //当前页码发生变化,调用此函数
    103. const onCurrentChange = (num) => {
    104. pageNum.value = num
    105. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
    106. }
    107. //1.3 搜索查询条件 文章列表查询
    108. const getArticleCategoryList = async () => {
    109. //获取所有分类
    110. let resultC = await articleCategoryListService();
    111. categorys.value = resultC.data
    112. }
    113. //1.4.2 获取文章列表数据
    114. const articleList = async () => {
    115. let params = {
    116. pageNum: pageNum.value,
    117. pageSize: pageSize.value,
    118. categoryId: categoryId.value ? categoryId.value : null,
    119. state: state.value ? state.value : null
    120. }
    121. let result = await articleListService(params);
    122. //渲染视图
    123. total.value = result.data.total;
    124. articles.value = result.data.items;
    125. //处理数据,给数据模型扩展一个属性categoryName,分类名称
    126. for (let i = 0; i < articles.value.length; i++) {
    127. let article = articles.value[i];
    128. for (let j = 0; j < categorys.value.length; j++) {
    129. if (article.categoryId == categorys.value[j].id) {
    130. article.categoryName = categorys.value[j].categoryName;
    131. }
    132. }
    133. }
    134. }
    135. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
    136. getArticleCategoryList();
    137. //1.4.2 获取文章列表数据
    138. articleList();
    139. </script>
    140. <template>
    141. <el-card class="page-container">
    142. <!-- 1 标题 -->
    143. <template #header>
    144. <div class="header">
    145. <span>文章管理</span>
    146. <div class="extra">
    147. <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件-->
    148. </div>
    149. </div>
    150. </template>
    151. <!-- 2 搜索表单 -->
    152. <el-form inline>
    153. <el-form-item label="文章分类:">
    154. <el-select placeholder="请选择" v-model="categoryId">
    155. <el-option
    156. v-for="c in categorys"
    157. :key="c.id"
    158. :label="c.categoryName"
    159. :value="c.id">
    160. </el-option>
    161. </el-select>
    162. </el-form-item>
    163. <el-form-item label="发布状态:">
    164. <el-select placeholder="请选择" v-model="state">
    165. <el-option label="已发布" value="已发布"></el-option>
    166. <el-option label="草稿" value="草稿"></el-option>
    167. </el-select>
    168. </el-form-item>
    169. <el-form-item>
    170. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
    171. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
    172. </el-form-item>
    173. </el-form>
    174. <!-- 3 文章列表 -->
    175. <el-table :data="articles" style="width: 100%">
    176. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
    177. <el-table-column label="分类" prop="categoryName"></el-table-column>
    178. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
    179. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
    180. <el-table-column label="状态" prop="state"></el-table-column>
    181. <el-table-column label="操作" width="100">
    182. <template #default="{ row }">
    183. <el-button :icon="Edit" circle plain type="primary"></el-button>
    184. <el-button :icon="Delete" circle plain type="danger"></el-button>
    185. </template>
    186. </el-table-column>
    187. <template #empty>
    188. <el-empty description="没有数据" />
    189. </template>
    190. </el-table>
    191. <!-- 4 分页条 -->
    192. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
    193. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
    194. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
    195. <!-- 七 3.1 抽屉 -->
    196. <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
    197. <!-- 添加文章表单 -->
    198. <el-form :model="articleModel" label-width="100px" >
    199. <el-form-item label="文章标题" >
    200. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
    201. </el-form-item>
    202. <el-form-item label="文章分类">
    203. <el-select placeholder="请选择" v-model="articleModel.categoryId">
    204. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
    205. </el-option>
    206. </el-select>
    207. </el-form-item>
    208. <el-form-item label="文章封面">
    209. <!--
    210. auto-upload:是否自动上传
    211. action: 服务器接口路径
    212. name: 上传的文件字段名
    213. headers: 设置上传的请求头
    214. on-success: 上传成功的回调函数 -->
    215. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
    216. action="/api/upload"
    217. name="file"
    218. :headers="{Authorization:tokenStore.token}"
    219. :on-success="uploadSuccess"
    220. >
    221. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
    222. <el-icon v-else class="avatar-uploader-icon">
    223. <Plus />
    224. </el-icon>
    225. </el-upload>
    226. </el-form-item>
    227. <el-form-item label="文章内容">
    228. <div class="editor">
    229. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
    230. </quill-editor>
    231. </div>
    232. </el-form-item>
    233. <el-form-item>
    234. <el-button type="primary">发布</el-button>
    235. <el-button type="info">草稿</el-button>
    236. </el-form-item>
    237. </el-form>
    238. </el-drawer>
    239. </el-card>
    240. </template>
    241. <style lang="scss" scoped>
    242. .page-container {
    243. min-height: 100%;
    244. box-sizing: border-box;
    245. .header {
    246. display: flex;
    247. align-items: center;
    248. justify-content: space-between;
    249. }
    250. }
    251. /*3.1 抽屉样式 */
    252. .avatar-uploader {
    253. :deep() {
    254. .avatar {
    255. width: 178px;
    256. height: 178px;
    257. display: block;
    258. }
    259. .el-upload {
    260. border: 1px dashed var(--el-border-color);
    261. border-radius: 6px;
    262. cursor: pointer;
    263. position: relative;
    264. overflow: hidden;
    265. transition: var(--el-transition-duration-fast);
    266. }
    267. .el-upload:hover {
    268. border-color: var(--el-color-primary);
    269. }
    270. .el-icon.avatar-uploader-icon {
    271. font-size: 28px;
    272. color: #8c939d;
    273. width: 178px;
    274. height: 178px;
    275. text-align: center;
    276. }
    277. }
    278. }
    279. .editor {
    280. width: 100%;
    281. :deep(.ql-editor) {
    282. min-height: 200px;
    283. }
    284. }
    285. //3.3.4 样式
    286. .editor {
    287. width: 100%;
    288. :deep(.ql-editor) {
    289. min-height: 200px;
    290. }
    291. }
    292. </style>

3.5 添加文章接口调用

3.5.1 article.js中提供添加文章函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
  22. //8.1 删除分类
  23. export const articleCategoryDeleteService = (id) => {
  24. return request.delete('/category?id='+id)
  25. }
  26. //1.4.1 文章列表查询
  27. export const articleListService = (params) => {
  28. return request.get('/article', { params: params })
  29. }
  30. //3.5.1添加文章
  31. export const articleAddService = (articleModel)=>{
  32. return request.post('/article',articleModel)
  33. }
3.5.2 为已发布和草稿按钮绑定事件
  1. <el-form-item>
  2. <el-button type="primary" @click="addArticle('已发布')">发布</el-button>
  3. <el-button type="info" @click="addArticle('草稿')">草稿</el-button>
  4. </el-form-item>
3.5.3 ArticleManage.vue中提供addArticle函数完成添加文章接口的调用
  1. const addArticle=async (state)=>{
  2. articleModel.value.state = state
  3. let result = await articleAddService(articleModel.value);
  4. ElMessage.success(result.message? result.message:'添加成功')
  5. //再次调用getArticles,获取文章
  6. articleList()
  7. //隐藏抽屉
  8. visibleDrawer.value=false
  9. }
  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //3.5.3
  8. import { ElMessage } from 'element-plus'
  9. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 七 1.4.2 articleListService 七3.5.1 articleAddService
  10. import { articleCategoryListService ,articleListService,articleAddService} from '@/api/article.js'
  11. //3.1 导入添加抽屉组件
  12. import {Plus} from '@element-plus/icons-vue'
  13. //3.3.2 导入组件和样式
  14. import { QuillEditor } from '@vueup/vue-quill'
  15. import '@vueup/vue-quill/dist/vue-quill.snow.css'
  16. //3.4 文章封面上传 导入token
  17. import { useTokenStore } from '@/stores/token.js'
  18. const tokenStore = useTokenStore();
  19. //3.4 上传图片成功回调
  20. const uploadSuccess = (img) => {
  21. //img就是后台响应的数据,格式为:{code:状态码,message:提示信息,data: 图片的存储地址}
  22. articleModel.value.coverImg=img.data
  23. }
  24. //3.1 控制抽屉是否显示
  25. const visibleDrawer = ref(false)
  26. //3.1 添加表单数据模型
  27. const articleModel = ref({
  28. title: '',
  29. categoryId: '',
  30. coverImg: '',
  31. content:'',
  32. state:''
  33. })
  34. //文章分类数据模型
  35. const categorys = ref([
  36. {
  37. "id": 3,
  38. "categoryName": "美食",
  39. "categoryAlias": "my",
  40. "createTime": "2023-09-02 12:06:59",
  41. "updateTime": "2023-09-02 12:06:59"
  42. },
  43. {
  44. "id": 4,
  45. "categoryName": "娱乐",
  46. "categoryAlias": "yl",
  47. "createTime": "2023-09-02 12:08:16",
  48. "updateTime": "2023-09-02 12:08:16"
  49. },
  50. {
  51. "id": 5,
  52. "categoryName": "军事",
  53. "categoryAlias": "js",
  54. "createTime": "2023-09-02 12:08:33",
  55. "updateTime": "2023-09-02 12:08:33"
  56. }
  57. ])
  58. //用户搜索时选中的分类id
  59. const categoryId=ref('')
  60. //用户搜索时选中的发布状态
  61. const state=ref('')
  62. //文章列表数据模型
  63. const articles = ref([
  64. {
  65. "id": 5,
  66. "title": "陕西旅游攻略",
  67. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  68. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  69. "state": "草稿",
  70. "categoryId": 2,
  71. "createTime": "2023-09-03 11:55:30",
  72. "updateTime": "2023-09-03 11:55:30"
  73. },
  74. {
  75. "id": 5,
  76. "title": "陕西旅游攻略",
  77. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  78. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  79. "state": "草稿",
  80. "categoryId": 2,
  81. "createTime": "2023-09-03 11:55:30",
  82. "updateTime": "2023-09-03 11:55:30"
  83. },
  84. {
  85. "id": 5,
  86. "title": "陕西旅游攻略",
  87. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  88. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  89. "state": "已发布",
  90. "categoryId": 2,
  91. "createTime": "2023-09-03 11:55:30",
  92. "updateTime": "2023-09-03 11:55:30"
  93. },
  94. ])
  95. //分页条数据模型
  96. const pageNum = ref(1)//当前页
  97. const total = ref(20)//总条数
  98. const pageSize = ref(3)//每页条数
  99. //当每页条数发生了变化,调用此函数
  100. const onSizeChange = (size) => {
  101. pageSize.value = size
  102. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  103. }
  104. //当前页码发生变化,调用此函数
  105. const onCurrentChange = (num) => {
  106. pageNum.value = num
  107. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  108. }
  109. //1.3 搜索查询条件 文章列表查询
  110. const getArticleCategoryList = async () => {
  111. //获取所有分类
  112. let resultC = await articleCategoryListService();
  113. categorys.value = resultC.data
  114. }
  115. //1.4.2 获取文章列表数据
  116. const articleList = async () => {
  117. let params = {
  118. pageNum: pageNum.value,
  119. pageSize: pageSize.value,
  120. categoryId: categoryId.value ? categoryId.value : null,
  121. state: state.value ? state.value : null
  122. }
  123. let result = await articleListService(params);
  124. //渲染视图
  125. total.value = result.data.total;
  126. articles.value = result.data.items;
  127. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  128. for (let i = 0; i < articles.value.length; i++) {
  129. let article = articles.value[i];
  130. for (let j = 0; j < categorys.value.length; j++) {
  131. if (article.categoryId == categorys.value[j].id) {
  132. article.categoryName = categorys.value[j].categoryName;
  133. }
  134. }
  135. }
  136. }
  137. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  138. getArticleCategoryList();
  139. //1.4.2 获取文章列表数据
  140. articleList();
  141. //3.5.3 添加文章
  142. const addArticle=async (state)=>{
  143. articleModel.value.state = state
  144. let result = await articleAddService(articleModel.value);
  145. ElMessage.success(result.message? result.message:'添加成功')
  146. //再次调用getArticles,获取文章
  147. articleList()
  148. //隐藏抽屉
  149. visibleDrawer.value=false
  150. }
  151. </script>
  152. <template>
  153. <el-card class="page-container">
  154. <!-- 1 标题 -->
  155. <template #header>
  156. <div class="header">
  157. <span>文章管理</span>
  158. <div class="extra">
  159. <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件-->
  160. </div>
  161. </div>
  162. </template>
  163. <!-- 2 搜索表单 -->
  164. <el-form inline>
  165. <el-form-item label="文章分类:">
  166. <el-select placeholder="请选择" v-model="categoryId">
  167. <el-option
  168. v-for="c in categorys"
  169. :key="c.id"
  170. :label="c.categoryName"
  171. :value="c.id">
  172. </el-option>
  173. </el-select>
  174. </el-form-item>
  175. <el-form-item label="发布状态:">
  176. <el-select placeholder="请选择" v-model="state">
  177. <el-option label="已发布" value="已发布"></el-option>
  178. <el-option label="草稿" value="草稿"></el-option>
  179. </el-select>
  180. </el-form-item>
  181. <el-form-item>
  182. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  183. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  184. </el-form-item>
  185. </el-form>
  186. <!-- 3 文章列表 -->
  187. <el-table :data="articles" style="width: 100%">
  188. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  189. <el-table-column label="分类" prop="categoryName"></el-table-column>
  190. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  191. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  192. <el-table-column label="状态" prop="state"></el-table-column>
  193. <el-table-column label="操作" width="100">
  194. <template #default="{ row }">
  195. <el-button :icon="Edit" circle plain type="primary"></el-button>
  196. <el-button :icon="Delete" circle plain type="danger"></el-button>
  197. </template>
  198. </el-table-column>
  199. <template #empty>
  200. <el-empty description="没有数据" />
  201. </template>
  202. </el-table>
  203. <!-- 4 分页条 -->
  204. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  205. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  206. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  207. <!-- 七 3.1 抽屉 -->
  208. <el-drawer v-model="visibleDrawer" title="添加文章" direction="rtl" size="50%">
  209. <!-- 添加文章表单 -->
  210. <el-form :model="articleModel" label-width="100px" >
  211. <el-form-item label="文章标题" >
  212. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  213. </el-form-item>
  214. <el-form-item label="文章分类">
  215. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  216. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  217. </el-option>
  218. </el-select>
  219. </el-form-item>
  220. <el-form-item label="文章封面">
  221. <!--
  222. auto-upload:是否自动上传
  223. action: 服务器接口路径
  224. name: 上传的文件字段名
  225. headers: 设置上传的请求头
  226. on-success: 上传成功的回调函数 -->
  227. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
  228. action="/api/upload"
  229. name="file"
  230. :headers="{Authorization:tokenStore.token}"
  231. :on-success="uploadSuccess"
  232. >
  233. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  234. <el-icon v-else class="avatar-uploader-icon">
  235. <Plus />
  236. </el-icon>
  237. </el-upload>
  238. </el-form-item>
  239. <el-form-item label="文章内容">
  240. <div class="editor">
  241. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
  242. </quill-editor>
  243. </div>
  244. </el-form-item>
  245. <el-form-item>
  246. <el-form-item>
  247. <el-button type="primary" @click="addArticle('已发布')">发布</el-button> <!-- 七 3.5.2 @click="addArticle('已发布')"-->
  248. <el-button type="info" @click="addArticle('草稿')">草稿</el-button> <!-- 七 3.5.2@click="addArticle('草稿')"-->
  249. </el-form-item>
  250. </el-form-item>
  251. </el-form>
  252. </el-drawer>
  253. </el-card>
  254. </template>
  255. <style lang="scss" scoped>
  256. .page-container {
  257. min-height: 100%;
  258. box-sizing: border-box;
  259. .header {
  260. display: flex;
  261. align-items: center;
  262. justify-content: space-between;
  263. }
  264. }
  265. /*3.1 抽屉样式 */
  266. .avatar-uploader {
  267. :deep() {
  268. .avatar {
  269. width: 178px;
  270. height: 178px;
  271. display: block;
  272. }
  273. .el-upload {
  274. border: 1px dashed var(--el-border-color);
  275. border-radius: 6px;
  276. cursor: pointer;
  277. position: relative;
  278. overflow: hidden;
  279. transition: var(--el-transition-duration-fast);
  280. }
  281. .el-upload:hover {
  282. border-color: var(--el-color-primary);
  283. }
  284. .el-icon.avatar-uploader-icon {
  285. font-size: 28px;
  286. color: #8c939d;
  287. width: 178px;
  288. height: 178px;
  289. text-align: center;
  290. }
  291. }
  292. }
  293. .editor {
  294. width: 100%;
  295. :deep(.ql-editor) {
  296. min-height: 200px;
  297. }
  298. }
  299. //3.3.4 样式
  300. .editor {
  301. width: 100%;
  302. :deep(.ql-editor) {
  303. min-height: 200px;
  304. }
  305. }
  306. </style>

4、编辑文章

4.1 修改文章抽屉页面

修改文章抽屉和新增文章抽屉长的一样,所以可以复用添加分类的弹窗

4.1.1 抽屉标题显示 定义标题
  1. //抽屉标题
  2. const title=ref('')
4.1.2 在抽屉上绑定标题
 <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
4.1.3 为添加文章按钮绑定事件
 <el-button type="primary" @click="title='添加文章';visibleDrawer = true">添加文章</el-button> 
4.1.4 为修改文章按钮绑定事件
 <el-button :icon="Edit" circle plain type="primary" @click="title='修改文章';visibleDrawer='true'"></el-button> 

4.2 数据回显

当点击修改文章按钮时,需要把当前这一条数据的详细信息显示到修改文章的抽屉上,这个叫回显

4.2.1 通过插槽的方式得到被点击按钮所在行的数据
  1. <template #default="{ row }">
  2. <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button> <!--七4.1.4 @click="title='修改文章';visibleDrawer='true'"4.2 showDrawer(row) -->
  3. <el-button :icon="Delete" circle plain type="danger"></el-button>
  4. </template>
4.2.2 回显函数
  1. //4.2.2展示抽屉弹窗
  2. const showDrawer = (row)=>{
  3. title.value = '修改文章';visibleDrawer.value = true
  4. //数据拷贝
  5. articleModel.value.title = row.title;
  6. articleModel.value.categoryId = row.categoryId;
  7. articleModel.value.coverImg = row.coverImg;
  8. articleModel.value.content = row.content;
  9. //扩展id属性,将来需要传参给后台完成文章的修改
  10. articleModel.value.id = row.id
  11. }
  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //3.5.3
  8. import { ElMessage } from 'element-plus'
  9. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 七 1.4.2 articleListService 七3.5.1 articleAddService
  10. import { articleCategoryListService ,articleListService,articleAddService} from '@/api/article.js'
  11. //3.1 导入添加抽屉组件
  12. import {Plus} from '@element-plus/icons-vue'
  13. //3.3.2 导入组件和样式
  14. import { QuillEditor } from '@vueup/vue-quill'
  15. import '@vueup/vue-quill/dist/vue-quill.snow.css'
  16. //3.4 文章封面上传 导入token
  17. import { useTokenStore } from '@/stores/token.js'
  18. const tokenStore = useTokenStore();
  19. //3.4 上传图片成功回调
  20. const uploadSuccess = (img) => {
  21. //img就是后台响应的数据,格式为:{code:状态码,message:提示信息,data: 图片的存储地址}
  22. articleModel.value.coverImg=img.data
  23. }
  24. //3.1 控制抽屉是否显示
  25. const visibleDrawer = ref(false)
  26. //3.1 添加表单数据模型
  27. const articleModel = ref({
  28. title: '',
  29. categoryId: '',
  30. coverImg: '',
  31. content:'',
  32. state:''
  33. })
  34. //文章分类数据模型
  35. const categorys = ref([
  36. {
  37. "id": 3,
  38. "categoryName": "美食",
  39. "categoryAlias": "my",
  40. "createTime": "2023-09-02 12:06:59",
  41. "updateTime": "2023-09-02 12:06:59"
  42. },
  43. {
  44. "id": 4,
  45. "categoryName": "娱乐",
  46. "categoryAlias": "yl",
  47. "createTime": "2023-09-02 12:08:16",
  48. "updateTime": "2023-09-02 12:08:16"
  49. },
  50. {
  51. "id": 5,
  52. "categoryName": "军事",
  53. "categoryAlias": "js",
  54. "createTime": "2023-09-02 12:08:33",
  55. "updateTime": "2023-09-02 12:08:33"
  56. }
  57. ])
  58. //用户搜索时选中的分类id
  59. const categoryId=ref('')
  60. //用户搜索时选中的发布状态
  61. const state=ref('')
  62. //文章列表数据模型
  63. const articles = ref([
  64. {
  65. "id": 5,
  66. "title": "陕西旅游攻略",
  67. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  68. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  69. "state": "草稿",
  70. "categoryId": 2,
  71. "createTime": "2023-09-03 11:55:30",
  72. "updateTime": "2023-09-03 11:55:30"
  73. },
  74. {
  75. "id": 5,
  76. "title": "陕西旅游攻略",
  77. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  78. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  79. "state": "草稿",
  80. "categoryId": 2,
  81. "createTime": "2023-09-03 11:55:30",
  82. "updateTime": "2023-09-03 11:55:30"
  83. },
  84. {
  85. "id": 5,
  86. "title": "陕西旅游攻略",
  87. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  88. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  89. "state": "已发布",
  90. "categoryId": 2,
  91. "createTime": "2023-09-03 11:55:30",
  92. "updateTime": "2023-09-03 11:55:30"
  93. },
  94. ])
  95. //分页条数据模型
  96. const pageNum = ref(1)//当前页
  97. const total = ref(20)//总条数
  98. const pageSize = ref(3)//每页条数
  99. //当每页条数发生了变化,调用此函数
  100. const onSizeChange = (size) => {
  101. pageSize.value = size
  102. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  103. }
  104. //当前页码发生变化,调用此函数
  105. const onCurrentChange = (num) => {
  106. pageNum.value = num
  107. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  108. }
  109. //1.3 搜索查询条件 文章列表查询
  110. const getArticleCategoryList = async () => {
  111. //获取所有分类
  112. let resultC = await articleCategoryListService();
  113. categorys.value = resultC.data
  114. }
  115. //1.4.2 获取文章列表数据
  116. const articleList = async () => {
  117. let params = {
  118. pageNum: pageNum.value,
  119. pageSize: pageSize.value,
  120. categoryId: categoryId.value ? categoryId.value : null,
  121. state: state.value ? state.value : null
  122. }
  123. let result = await articleListService(params);
  124. //渲染视图
  125. total.value = result.data.total;
  126. articles.value = result.data.items;
  127. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  128. for (let i = 0; i < articles.value.length; i++) {
  129. let article = articles.value[i];
  130. for (let j = 0; j < categorys.value.length; j++) {
  131. if (article.categoryId == categorys.value[j].id) {
  132. article.categoryName = categorys.value[j].categoryName;
  133. }
  134. }
  135. }
  136. }
  137. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  138. getArticleCategoryList();
  139. //1.4.2 获取文章列表数据
  140. articleList();
  141. //3.5.3 添加文章
  142. const addArticle=async (state)=>{
  143. articleModel.value.state = state
  144. let result = await articleAddService(articleModel.value);
  145. ElMessage.success(result.message? result.message:'添加成功')
  146. //再次调用getArticles,获取文章
  147. articleList()
  148. //隐藏抽屉
  149. visibleDrawer.value=false
  150. }
  151. //<!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  152. const title=ref('')
  153. //4.2.2展示抽屉弹窗
  154. const showDrawer = (row)=>{
  155. title.value = '修改文章';visibleDrawer.value = true
  156. //数据拷贝
  157. articleModel.value.title = row.title;
  158. articleModel.value.categoryId = row.categoryId;
  159. articleModel.value.coverImg = row.coverImg;
  160. articleModel.value.content = row.content;
  161. //扩展id属性,将来需要传参给后台完成文章的修改
  162. articleModel.value.id = row.id
  163. }
  164. </script>
  165. <template>
  166. <el-card class="page-container">
  167. <!-- 1 标题 -->
  168. <template #header>
  169. <div class="header">
  170. <span>文章管理</span>
  171. <div class="extra">
  172. <el-button type="primary" @click="title='添加文章';visibleDrawer = true">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件 七 4.1.3 title='添加文章'; -->
  173. </div>
  174. </div>
  175. </template>
  176. <!-- 2 搜索表单 -->
  177. <el-form inline>
  178. <el-form-item label="文章分类:">
  179. <el-select placeholder="请选择" v-model="categoryId">
  180. <el-option
  181. v-for="c in categorys"
  182. :key="c.id"
  183. :label="c.categoryName"
  184. :value="c.id">
  185. </el-option>
  186. </el-select>
  187. </el-form-item>
  188. <el-form-item label="发布状态:">
  189. <el-select placeholder="请选择" v-model="state">
  190. <el-option label="已发布" value="已发布"></el-option>
  191. <el-option label="草稿" value="草稿"></el-option>
  192. </el-select>
  193. </el-form-item>
  194. <el-form-item>
  195. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  196. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  197. </el-form-item>
  198. </el-form>
  199. <!-- 3 文章列表 -->
  200. <el-table :data="articles" style="width: 100%">
  201. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  202. <el-table-column label="分类" prop="categoryName"></el-table-column>
  203. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  204. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  205. <el-table-column label="状态" prop="state"></el-table-column>
  206. <el-table-column label="操作" width="100">
  207. <template #default="{ row }">
  208. <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button> <!--七4.1.4 @click="title='修改文章';visibleDrawer='true'"4.2.1 showDrawer(row) -->
  209. <el-button :icon="Delete" circle plain type="danger"></el-button>
  210. </template>
  211. </el-table-column>
  212. <template #empty>
  213. <el-empty description="没有数据" />
  214. </template>
  215. </el-table>
  216. <!-- 4 分页条 -->
  217. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  218. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  219. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  220. <!-- 七 3.1 抽屉 -->
  221. <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%"> <!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  222. <!-- 添加文章表单 -->
  223. <el-form :model="articleModel" label-width="100px" >
  224. <el-form-item label="文章标题" >
  225. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  226. </el-form-item>
  227. <el-form-item label="文章分类">
  228. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  229. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  230. </el-option>
  231. </el-select>
  232. </el-form-item>
  233. <el-form-item label="文章封面">
  234. <!--
  235. auto-upload:是否自动上传
  236. action: 服务器接口路径
  237. name: 上传的文件字段名
  238. headers: 设置上传的请求头
  239. on-success: 上传成功的回调函数 -->
  240. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
  241. action="/api/upload"
  242. name="file"
  243. :headers="{Authorization:tokenStore.token}"
  244. :on-success="uploadSuccess"
  245. >
  246. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  247. <el-icon v-else class="avatar-uploader-icon">
  248. <Plus />
  249. </el-icon>
  250. </el-upload>
  251. </el-form-item>
  252. <el-form-item label="文章内容">
  253. <div class="editor">
  254. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
  255. </quill-editor>
  256. </div>
  257. </el-form-item>
  258. <el-form-item>
  259. <el-form-item>
  260. <el-button type="primary" @click="addArticle('已发布')">发布</el-button> <!-- 七 3.5.2 @click="addArticle('已发布')"-->
  261. <el-button type="info" @click="addArticle('草稿')">草稿</el-button> <!-- 七 3.5.2@click="addArticle('草稿')"-->
  262. </el-form-item>
  263. </el-form-item>
  264. </el-form>
  265. </el-drawer>
  266. </el-card>
  267. </template>
  268. <style lang="scss" scoped>
  269. .page-container {
  270. min-height: 100%;
  271. box-sizing: border-box;
  272. .header {
  273. display: flex;
  274. align-items: center;
  275. justify-content: space-between;
  276. }
  277. }
  278. /*3.1 抽屉样式 */
  279. .avatar-uploader {
  280. :deep() {
  281. .avatar {
  282. width: 178px;
  283. height: 178px;
  284. display: block;
  285. }
  286. .el-upload {
  287. border: 1px dashed var(--el-border-color);
  288. border-radius: 6px;
  289. cursor: pointer;
  290. position: relative;
  291. overflow: hidden;
  292. transition: var(--el-transition-duration-fast);
  293. }
  294. .el-upload:hover {
  295. border-color: var(--el-color-primary);
  296. }
  297. .el-icon.avatar-uploader-icon {
  298. font-size: 28px;
  299. color: #8c939d;
  300. width: 178px;
  301. height: 178px;
  302. text-align: center;
  303. }
  304. }
  305. }
  306. .editor {
  307. width: 100%;
  308. :deep(.ql-editor) {
  309. min-height: 200px;
  310. }
  311. }
  312. //3.3.4 样式
  313. .editor {
  314. width: 100%;
  315. :deep(.ql-editor) {
  316. min-height: 200px;
  317. }
  318. }
  319. </style>

4.3 修改文章接口调用

4.3.1 article.js中提供修改文章的函数
  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
  22. //8.1 删除分类
  23. export const articleCategoryDeleteService = (id) => {
  24. return request.delete('/category?id='+id)
  25. }
  26. //1.4.1 文章列表查询
  27. export const articleListService = (params) => {
  28. return request.get('/article', { params: params })
  29. }
  30. //3.5.1添加文章
  31. export const articleAddService = (articleModel)=>{
  32. return request.post('/article',articleModel)
  33. }
  34. //4.3.1修改文章
  35. export const articleUpdateService = (articleModel)=>{
  36. return request.put('/article',articleModel)
  37. }
4.3.2 修改发布与草稿按钮的绑定事件
  1. <el-form-item>
  2. <el-button type="primary" @click="title==='添加文章'? addArticle('已发布'): updateArticle('已发布')">发布</el-button> <!-- 七 3.5.2 @click="addArticle('已发布') 七 4.3.2 ;title==='添加文章'? addArticle('已发布'):updateArticle('已发布')"-->
  3. <el-button type="info" @click="title==='添加文章'? addArticle('草稿'): updateArticle('草稿')">草稿</el-button> <!-- 七 3.5.2@click="addArticle('草稿')"4.3.2 ;title==='添加文章'? addArticle('草稿'):updateArticle('草稿')-->
  4. </el-form-item>
4.3.3 调用接口完成修改的函数
  1. //4.4.4 修改文章
  2. const updateArticle=async ()=>{
  3. let result = await articleUpdateService(articleModel.value)
  4. ElMessage.success(result.message? result.message:'修改成功')
  5. //隐藏抽屉
  6. visibleDrawer.value=false
  7. //再次访问后台接口,查询所有文章
  8. articleList()
  9. }

由于现在修改和新增共用了一个数据模型,所以在点击添加文章后,有时候会显示数据,此时可以将articleModel中的数据清空

  1. //4.4.3 清空模型数据
  2. const clearArticleModel = ()=>{
  3. articleModel.value.title='',
  4. articleModel.value.categoryId='',
  5. articleModel.value.coverImg='',
  6. articleModel.value.content='<br>',
  7. articleModel.value.state=''
  8. }

修改 添加文章按钮的点击事件()

<el-button type="primary" @click="title='添加文章';visibleDrawer = true;clearArticleModel()">添加文章</el-button>  <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件 七 4.1.3 title='添加文章';  七 4.3.3 ;clearArticleModel() -->
  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //3.5.3
  8. import { ElMessage } from 'element-plus'
  9. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 七 1.4.2 articleListService 七3.5.1 articleAddService 七 4.3.3articleUpdateService
  10. import { articleCategoryListService ,articleListService,articleAddService,articleUpdateService} from '@/api/article.js'
  11. //3.1 导入添加抽屉组件
  12. import {Plus} from '@element-plus/icons-vue'
  13. //3.3.2 导入组件和样式
  14. import { QuillEditor } from '@vueup/vue-quill'
  15. import '@vueup/vue-quill/dist/vue-quill.snow.css'
  16. //3.4 文章封面上传 导入token
  17. import { useTokenStore } from '@/stores/token.js'
  18. const tokenStore = useTokenStore();
  19. //3.4 上传图片成功回调
  20. const uploadSuccess = (img) => {
  21. //img就是后台响应的数据,格式为:{code:状态码,message:提示信息,data: 图片的存储地址}
  22. articleModel.value.coverImg=img.data
  23. }
  24. //3.1 控制抽屉是否显示
  25. const visibleDrawer = ref(false)
  26. //3.1 添加表单数据模型
  27. const articleModel = ref({
  28. title: '',
  29. categoryId: '',
  30. coverImg: '',
  31. content:'',
  32. state:''
  33. })
  34. //文章分类数据模型
  35. const categorys = ref([
  36. {
  37. "id": 3,
  38. "categoryName": "美食",
  39. "categoryAlias": "my",
  40. "createTime": "2023-09-02 12:06:59",
  41. "updateTime": "2023-09-02 12:06:59"
  42. },
  43. {
  44. "id": 4,
  45. "categoryName": "娱乐",
  46. "categoryAlias": "yl",
  47. "createTime": "2023-09-02 12:08:16",
  48. "updateTime": "2023-09-02 12:08:16"
  49. },
  50. {
  51. "id": 5,
  52. "categoryName": "军事",
  53. "categoryAlias": "js",
  54. "createTime": "2023-09-02 12:08:33",
  55. "updateTime": "2023-09-02 12:08:33"
  56. }
  57. ])
  58. //用户搜索时选中的分类id
  59. const categoryId=ref('')
  60. //用户搜索时选中的发布状态
  61. const state=ref('')
  62. //文章列表数据模型
  63. const articles = ref([
  64. {
  65. "id": 5,
  66. "title": "陕西旅游攻略",
  67. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  68. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  69. "state": "草稿",
  70. "categoryId": 2,
  71. "createTime": "2023-09-03 11:55:30",
  72. "updateTime": "2023-09-03 11:55:30"
  73. },
  74. {
  75. "id": 5,
  76. "title": "陕西旅游攻略",
  77. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  78. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  79. "state": "草稿",
  80. "categoryId": 2,
  81. "createTime": "2023-09-03 11:55:30",
  82. "updateTime": "2023-09-03 11:55:30"
  83. },
  84. {
  85. "id": 5,
  86. "title": "陕西旅游攻略",
  87. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  88. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  89. "state": "已发布",
  90. "categoryId": 2,
  91. "createTime": "2023-09-03 11:55:30",
  92. "updateTime": "2023-09-03 11:55:30"
  93. },
  94. ])
  95. //分页条数据模型
  96. const pageNum = ref(1)//当前页
  97. const total = ref(20)//总条数
  98. const pageSize = ref(3)//每页条数
  99. //当每页条数发生了变化,调用此函数
  100. const onSizeChange = (size) => {
  101. pageSize.value = size
  102. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  103. }
  104. //当前页码发生变化,调用此函数
  105. const onCurrentChange = (num) => {
  106. pageNum.value = num
  107. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  108. }
  109. //1.3 搜索查询条件 文章列表查询
  110. const getArticleCategoryList = async () => {
  111. //获取所有分类
  112. let resultC = await articleCategoryListService();
  113. categorys.value = resultC.data
  114. }
  115. //1.4.2 获取文章列表数据
  116. const articleList = async () => {
  117. let params = {
  118. pageNum: pageNum.value,
  119. pageSize: pageSize.value,
  120. categoryId: categoryId.value ? categoryId.value : null,
  121. state: state.value ? state.value : null
  122. }
  123. let result = await articleListService(params);
  124. //渲染视图
  125. total.value = result.data.total;
  126. articles.value = result.data.items;
  127. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  128. for (let i = 0; i < articles.value.length; i++) {
  129. let article = articles.value[i];
  130. for (let j = 0; j < categorys.value.length; j++) {
  131. if (article.categoryId == categorys.value[j].id) {
  132. article.categoryName = categorys.value[j].categoryName;
  133. }
  134. }
  135. }
  136. }
  137. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  138. getArticleCategoryList();
  139. //1.4.2 获取文章列表数据
  140. articleList();
  141. //3.5.3 添加文章
  142. const addArticle=async (state)=>{
  143. articleModel.value.state = state
  144. let result = await articleAddService(articleModel.value);
  145. ElMessage.success(result.message? result.message:'添加成功')
  146. //再次调用getArticles,获取文章
  147. articleList()
  148. //隐藏抽屉
  149. visibleDrawer.value=false
  150. }
  151. //<!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  152. const title=ref('')
  153. //4.2.2展示抽屉弹窗
  154. const showDrawer = (row)=>{
  155. title.value = '修改文章';visibleDrawer.value = true
  156. //数据拷贝
  157. articleModel.value.title = row.title;
  158. articleModel.value.categoryId = row.categoryId;
  159. articleModel.value.coverImg = row.coverImg;
  160. articleModel.value.content = row.content;
  161. //扩展id属性,将来需要传参给后台完成文章的修改
  162. articleModel.value.id = row.id
  163. }
  164. //4.4.3 修改文章
  165. const updateArticle=async ()=>{
  166. let result = await articleUpdateService(articleModel.value)
  167. ElMessage.success(result.message? result.message:'修改成功')
  168. //隐藏抽屉
  169. visibleDrawer.value=false
  170. //再次访问后台接口,查询所有文章
  171. articleList()
  172. }
  173. //4.4.3 清空模型数据
  174. const clearArticleModel = ()=>{
  175. articleModel.value.title='',
  176. articleModel.value.categoryId='',
  177. articleModel.value.coverImg='',
  178. articleModel.value.content=' ', // 这里清空不了富文本,没有找到解决方案 暂时多了一个空格处理
  179. articleModel.value.state=''
  180. }
  181. </script>
  182. <template>
  183. <el-card class="page-container">
  184. <!-- 1 标题 -->
  185. <template #header>
  186. <div class="header">
  187. <span>文章管理</span>
  188. <div class="extra">
  189. <el-button type="primary" @click="title='添加文章';visibleDrawer = true;clearArticleModel()">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件 七 4.1.3 title='添加文章'; 七 4.3.3 ;clearArticleModel() -->
  190. </div>
  191. </div>
  192. </template>
  193. <!-- 2 搜索表单 -->
  194. <el-form inline>
  195. <el-form-item label="文章分类:">
  196. <el-select placeholder="请选择" v-model="categoryId">
  197. <el-option
  198. v-for="c in categorys"
  199. :key="c.id"
  200. :label="c.categoryName"
  201. :value="c.id">
  202. </el-option>
  203. </el-select>
  204. </el-form-item>
  205. <el-form-item label="发布状态:">
  206. <el-select placeholder="请选择" v-model="state">
  207. <el-option label="已发布" value="已发布"></el-option>
  208. <el-option label="草稿" value="草稿"></el-option>
  209. </el-select>
  210. </el-form-item>
  211. <el-form-item>
  212. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  213. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  214. </el-form-item>
  215. </el-form>
  216. <!-- 3 文章列表 -->
  217. <el-table :data="articles" style="width: 100%">
  218. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  219. <el-table-column label="分类" prop="categoryName"></el-table-column>
  220. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  221. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  222. <el-table-column label="状态" prop="state"></el-table-column>
  223. <el-table-column label="操作" width="100">
  224. <template #default="{ row }">
  225. <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button> <!--七4.1.4 @click="title='修改文章';visibleDrawer='true'"4.2.1 showDrawer(row) -->
  226. <el-button :icon="Delete" circle plain type="danger"></el-button>
  227. </template>
  228. </el-table-column>
  229. <template #empty>
  230. <el-empty description="没有数据" />
  231. </template>
  232. </el-table>
  233. <!-- 4 分页条 -->
  234. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  235. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  236. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  237. <!-- 七 3.1 抽屉 -->
  238. <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%"> <!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  239. <!-- 添加文章表单 -->
  240. <el-form :model="articleModel" label-width="100px" >
  241. <el-form-item label="文章标题" >
  242. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  243. </el-form-item>
  244. <el-form-item label="文章分类">
  245. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  246. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  247. </el-option>
  248. </el-select>
  249. </el-form-item>
  250. <el-form-item label="文章封面">
  251. <!--
  252. auto-upload:是否自动上传
  253. action: 服务器接口路径
  254. name: 上传的文件字段名
  255. headers: 设置上传的请求头
  256. on-success: 上传成功的回调函数 -->
  257. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
  258. action="/api/upload"
  259. name="file"
  260. :headers="{Authorization:tokenStore.token}"
  261. :on-success="uploadSuccess"
  262. >
  263. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  264. <el-icon v-else class="avatar-uploader-icon">
  265. <Plus />
  266. </el-icon>
  267. </el-upload>
  268. </el-form-item>
  269. <el-form-item label="文章内容">
  270. <div class="editor">
  271. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
  272. </quill-editor>
  273. </div>
  274. </el-form-item>
  275. <el-form-item>
  276. <el-form-item>
  277. <el-button type="primary" @click="title==='添加文章'? addArticle('已发布'): updateArticle('已发布')">发布</el-button> <!-- 七 3.5.2 @click="addArticle('已发布') 七 4.3.2 ;title==='添加文章'? addArticle('已发布'):updateArticle('已发布')"-->
  278. <el-button type="info" @click="title==='添加文章'? addArticle('草稿'): updateArticle('草稿')">草稿</el-button> <!-- 七 3.5.2@click="addArticle('草稿')"4.3.2 ;title==='添加文章'? addArticle('草稿'):updateArticle('草稿')-->
  279. </el-form-item>
  280. </el-form-item>
  281. </el-form>
  282. </el-drawer>
  283. </el-card>
  284. </template>
  285. <style lang="scss" scoped>
  286. .page-container {
  287. min-height: 100%;
  288. box-sizing: border-box;
  289. .header {
  290. display: flex;
  291. align-items: center;
  292. justify-content: space-between;
  293. }
  294. }
  295. /*3.1 抽屉样式 */
  296. .avatar-uploader {
  297. :deep() {
  298. .avatar {
  299. width: 178px;
  300. height: 178px;
  301. display: block;
  302. }
  303. .el-upload {
  304. border: 1px dashed var(--el-border-color);
  305. border-radius: 6px;
  306. cursor: pointer;
  307. position: relative;
  308. overflow: hidden;
  309. transition: var(--el-transition-duration-fast);
  310. }
  311. .el-upload:hover {
  312. border-color: var(--el-color-primary);
  313. }
  314. .el-icon.avatar-uploader-icon {
  315. font-size: 28px;
  316. color: #8c939d;
  317. width: 178px;
  318. height: 178px;
  319. text-align: center;
  320. }
  321. }
  322. }
  323. .editor {
  324. width: 100%;
  325. :deep(.ql-editor) {
  326. min-height: 200px;
  327. }
  328. }
  329. //3.3.4 样式
  330. .editor {
  331. width: 100%;
  332. :deep(.ql-editor) {
  333. min-height: 200px;
  334. }
  335. }
  336. </style>

5、删除文章

5.1 接口调用

article.js中提供删除分类的函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. //2.4 导入@/stores/token.js
  4. import { useTokenStore } from '@/stores/token.js'
  5. // 六 文章分类列表查询函数
  6. export const articleCategoryListService = (registerData) =>{
  7. //2.4获取token状态
  8. //3.2
  9. // const tokenStore = useTokenStore()
  10. //通过请求头Authorization携带token
  11. // return request.get('/category', { headers: { 'Authorization': tokenStore.token } });
  12. return request.get('/category');
  13. }
  14. //6.2 文章分类 添加文章分类 函数 json 参数
  15. export const articleCategoryAddService = (categoryModel) => {
  16. return request.post('/category', categoryModel)
  17. }
  18. //7.3.1 修改分类
  19. export const articleCategoryUpdateService = (categoryModel)=>{
  20. return request.put('/category',categoryModel)
  21. }
  22. //8.1 删除分类
  23. export const articleCategoryDeleteService = (id) => {
  24. return request.delete('/category?id='+id)
  25. }
  26. //1.4.1 文章列表查询
  27. export const articleListService = (params) => {
  28. return request.get('/article', { params: params })
  29. }
  30. //3.5.1添加文章
  31. export const articleAddService = (articleModel)=>{
  32. return request.post('/article',articleModel)
  33. }
  34. //4.3.1修改文章
  35. export const articleUpdateService = (articleModel)=>{
  36. return request.put('/article',articleModel)
  37. }
  38. //5.1删除文章
  39. export const articleDeleteService = (id) => {
  40. return request.delete('/article?id='+id)
  41. }

5.2 为删除按钮绑定事件

  1. <template #default="{ row }">
  2. <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button> <!--七4.1.4 @click="title='修改文章';visibleDrawer='true'"4.2.1 showDrawer(row) -->
  3. <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button> <!-- 七 5.2 为删除按钮绑定事件-->
  4. </template>

5.3 添加删除弹窗,当用户点击确认后,调用接口删除分类

  1. <script setup>
  2. import {
  3. Edit,
  4. Delete
  5. } from '@element-plus/icons-vue'
  6. import { ref } from 'vue'
  7. //3.5.3
  8. import { ElMessage,ElMessageBox } from 'element-plus'
  9. //1.3 articleCategoryListService搜索查询条件 文章列表查询 导入 七 1.4.2 articleListService 七3.5.1 articleAddService 七 4.3.3articleUpdateService 七 5.3 articleDeleteService
  10. import { articleCategoryListService ,articleListService,articleAddService,articleUpdateService,articleDeleteService} from '@/api/article.js'
  11. //3.1 导入添加抽屉组件
  12. import {Plus} from '@element-plus/icons-vue'
  13. //3.3.2 导入组件和样式
  14. import { QuillEditor } from '@vueup/vue-quill'
  15. import '@vueup/vue-quill/dist/vue-quill.snow.css'
  16. //3.4 文章封面上传 导入token
  17. import { useTokenStore } from '@/stores/token.js'
  18. const tokenStore = useTokenStore();
  19. //3.4 上传图片成功回调
  20. const uploadSuccess = (img) => {
  21. //img就是后台响应的数据,格式为:{code:状态码,message:提示信息,data: 图片的存储地址}
  22. articleModel.value.coverImg=img.data
  23. }
  24. //3.1 控制抽屉是否显示
  25. const visibleDrawer = ref(false)
  26. //3.1 添加表单数据模型
  27. const articleModel = ref({
  28. title: '',
  29. categoryId: '',
  30. coverImg: '',
  31. content:'',
  32. state:''
  33. })
  34. //文章分类数据模型
  35. const categorys = ref([
  36. {
  37. "id": 3,
  38. "categoryName": "美食",
  39. "categoryAlias": "my",
  40. "createTime": "2023-09-02 12:06:59",
  41. "updateTime": "2023-09-02 12:06:59"
  42. },
  43. {
  44. "id": 4,
  45. "categoryName": "娱乐",
  46. "categoryAlias": "yl",
  47. "createTime": "2023-09-02 12:08:16",
  48. "updateTime": "2023-09-02 12:08:16"
  49. },
  50. {
  51. "id": 5,
  52. "categoryName": "军事",
  53. "categoryAlias": "js",
  54. "createTime": "2023-09-02 12:08:33",
  55. "updateTime": "2023-09-02 12:08:33"
  56. }
  57. ])
  58. //用户搜索时选中的分类id
  59. const categoryId=ref('')
  60. //用户搜索时选中的发布状态
  61. const state=ref('')
  62. //文章列表数据模型
  63. const articles = ref([
  64. {
  65. "id": 5,
  66. "title": "陕西旅游攻略",
  67. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  68. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  69. "state": "草稿",
  70. "categoryId": 2,
  71. "createTime": "2023-09-03 11:55:30",
  72. "updateTime": "2023-09-03 11:55:30"
  73. },
  74. {
  75. "id": 5,
  76. "title": "陕西旅游攻略",
  77. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  78. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  79. "state": "草稿",
  80. "categoryId": 2,
  81. "createTime": "2023-09-03 11:55:30",
  82. "updateTime": "2023-09-03 11:55:30"
  83. },
  84. {
  85. "id": 5,
  86. "title": "陕西旅游攻略",
  87. "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
  88. "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
  89. "state": "已发布",
  90. "categoryId": 2,
  91. "createTime": "2023-09-03 11:55:30",
  92. "updateTime": "2023-09-03 11:55:30"
  93. },
  94. ])
  95. //分页条数据模型
  96. const pageNum = ref(1)//当前页
  97. const total = ref(20)//总条数
  98. const pageSize = ref(3)//每页条数
  99. //当每页条数发生了变化,调用此函数
  100. const onSizeChange = (size) => {
  101. pageSize.value = size
  102. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  103. }
  104. //当前页码发生变化,调用此函数
  105. const onCurrentChange = (num) => {
  106. pageNum.value = num
  107. articleList() //1.4.3 **当分页条的当前页和每页条数发生变化,重新发送请求获取数据**
  108. }
  109. //1.3 搜索查询条件 文章列表查询
  110. const getArticleCategoryList = async () => {
  111. //获取所有分类
  112. let resultC = await articleCategoryListService();
  113. categorys.value = resultC.data
  114. }
  115. //1.4.2 获取文章列表数据
  116. const articleList = async () => {
  117. let params = {
  118. pageNum: pageNum.value,
  119. pageSize: pageSize.value,
  120. categoryId: categoryId.value ? categoryId.value : null,
  121. state: state.value ? state.value : null
  122. }
  123. let result = await articleListService(params);
  124. //渲染视图
  125. total.value = result.data.total;
  126. articles.value = result.data.items;
  127. //处理数据,给数据模型扩展一个属性categoryName,分类名称
  128. for (let i = 0; i < articles.value.length; i++) {
  129. let article = articles.value[i];
  130. for (let j = 0; j < categorys.value.length; j++) {
  131. if (article.categoryId == categorys.value[j].id) {
  132. article.categoryName = categorys.value[j].categoryName;
  133. }
  134. }
  135. }
  136. }
  137. //1.3 搜索查询条件 文章列表查询 调用函数getArticleCategoryList
  138. getArticleCategoryList();
  139. //1.4.2 获取文章列表数据
  140. articleList();
  141. //3.5.3 添加文章
  142. const addArticle=async (state)=>{
  143. articleModel.value.state = state
  144. let result = await articleAddService(articleModel.value);
  145. ElMessage.success(result.message? result.message:'添加成功')
  146. //再次调用getArticles,获取文章
  147. articleList()
  148. //隐藏抽屉
  149. visibleDrawer.value=false
  150. }
  151. //<!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  152. const title=ref('')
  153. //4.2.2展示抽屉弹窗
  154. const showDrawer = (row)=>{
  155. title.value = '修改文章';visibleDrawer.value = true
  156. //数据拷贝
  157. articleModel.value.title = row.title;
  158. articleModel.value.categoryId = row.categoryId;
  159. articleModel.value.coverImg = row.coverImg;
  160. articleModel.value.content = row.content;
  161. //扩展id属性,将来需要传参给后台完成文章的修改
  162. articleModel.value.id = row.id
  163. }
  164. //4.4.3 修改文章
  165. const updateArticle=async (state)=>{
  166. articleModel.value.state = state
  167. let result = await articleUpdateService(articleModel.value)
  168. ElMessage.success(result.message? result.message:'修改成功')
  169. //隐藏抽屉
  170. visibleDrawer.value=false
  171. //再次访问后台接口,查询所有文章
  172. articleList()
  173. }
  174. //4.4.3 清空模型数据
  175. const clearArticleModel = ()=>{
  176. articleModel.value.title='',
  177. articleModel.value.categoryId='',
  178. articleModel.value.coverImg='',
  179. articleModel.value.content=' ', // 这里清空不了富文本,没有找到解决方案 暂时多了一个空格处理
  180. articleModel.value.state=''
  181. }
  182. //5.3 删除文章(记得引用ElMessageBox) 给删除按钮绑定事件
  183. const deleteArticle = (row) => {
  184. // 提示用户 确认框
  185. ElMessageBox.confirm(
  186. '你确认删除该文章信息吗?',
  187. '温馨提示',
  188. {
  189. confirmButtonText: '确认',
  190. cancelButtonText: '取消',
  191. type: 'warning',
  192. }
  193. )
  194. .then(async() => {
  195. //用户点击了确认
  196. let result = await articleDeleteService(row.id)
  197. // 给出提示
  198. ElMessage({
  199. type: 'success',
  200. message: '删除成功',
  201. })
  202. //刷新列表//再次访问后台接口,查询所有文章
  203. articleList()
  204. })
  205. .catch(() => {
  206. //用户点击了取消
  207. ElMessage({
  208. type: 'info',
  209. message: '取消删除',
  210. })
  211. })
  212. }
  213. </script>
  214. <template>
  215. <el-card class="page-container">
  216. <!-- 1 标题 -->
  217. <template #header>
  218. <div class="header">
  219. <span>文章管理</span>
  220. <div class="extra">
  221. <el-button type="primary" @click="title='添加文章';visibleDrawer = true;clearArticleModel()">添加文章</el-button> <!-- 七 3.2 @click="visibleDrawer = true" 绑定查询事件 七 4.1.3 title='添加文章'; 七 4.3.3 ;clearArticleModel() -->
  222. </div>
  223. </div>
  224. </template>
  225. <!-- 2 搜索表单 -->
  226. <el-form inline>
  227. <el-form-item label="文章分类:">
  228. <el-select placeholder="请选择" v-model="categoryId">
  229. <el-option
  230. v-for="c in categorys"
  231. :key="c.id"
  232. :label="c.categoryName"
  233. :value="c.id">
  234. </el-option>
  235. </el-select>
  236. </el-form-item>
  237. <el-form-item label="发布状态:">
  238. <el-select placeholder="请选择" v-model="state">
  239. <el-option label="已发布" value="已发布"></el-option>
  240. <el-option label="草稿" value="草稿"></el-option>
  241. </el-select>
  242. </el-form-item>
  243. <el-form-item>
  244. <el-button type="primary" @click="articleList">搜索</el-button> <!-- 七 2 绑定查询事件-->
  245. <el-button @click="categoryId='';state='';articleList()">重置</el-button> <!-- 七 2 绑定重置事件-->
  246. </el-form-item>
  247. </el-form>
  248. <!-- 3 文章列表 -->
  249. <el-table :data="articles" style="width: 100%">
  250. <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
  251. <el-table-column label="分类" prop="categoryName"></el-table-column>
  252. <el-table-column label="发表时间" prop="createTime"> </el-table-column>
  253. <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
  254. <el-table-column label="状态" prop="state"></el-table-column>
  255. <el-table-column label="操作" width="100">
  256. <template #default="{ row }">
  257. <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button> <!--七4.1.4 @click="title='修改文章';visibleDrawer='true'"4.2.1 showDrawer(row) -->
  258. <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button> <!-- 七 5.2 为删除按钮绑定事件-->
  259. </template>
  260. </el-table-column>
  261. <template #empty>
  262. <el-empty description="没有数据" />
  263. </template>
  264. </el-table>
  265. <!-- 4 分页条 -->
  266. <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[3, 5 ,10, 15]"
  267. layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
  268. @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />
  269. <!-- 七 3.1 抽屉 -->
  270. <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%"> <!-- 七 4.1 抽屉:title="title" -绑定标题 -->
  271. <!-- 添加文章表单 -->
  272. <el-form :model="articleModel" label-width="100px" >
  273. <el-form-item label="文章标题" >
  274. <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
  275. </el-form-item>
  276. <el-form-item label="文章分类">
  277. <el-select placeholder="请选择" v-model="articleModel.categoryId">
  278. <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id">
  279. </el-option>
  280. </el-select>
  281. </el-form-item>
  282. <el-form-item label="文章封面">
  283. <!--
  284. auto-upload:是否自动上传
  285. action: 服务器接口路径
  286. name: 上传的文件字段名
  287. headers: 设置上传的请求头
  288. on-success: 上传成功的回调函数 -->
  289. <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
  290. action="/api/upload"
  291. name="file"
  292. :headers="{Authorization:tokenStore.token}"
  293. :on-success="uploadSuccess"
  294. >
  295. <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
  296. <el-icon v-else class="avatar-uploader-icon">
  297. <Plus />
  298. </el-icon>
  299. </el-upload>
  300. </el-form-item>
  301. <el-form-item label="文章内容">
  302. <div class="editor">
  303. <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html"> <!-- 七 3.3.3页面使用quill组件 -->
  304. </quill-editor>
  305. </div>
  306. </el-form-item>
  307. <el-form-item>
  308. <el-form-item>
  309. <el-button type="primary" @click="title==='添加文章'? addArticle('已发布'): updateArticle('已发布')">发布</el-button> <!-- 七 3.5.2 @click="addArticle('已发布') 七 4.3.2 ;title==='添加文章'? addArticle('已发布'):updateArticle('已发布')"-->
  310. <el-button type="info" @click="title==='添加文章'? addArticle('草稿'): updateArticle('草稿')">草稿</el-button> <!-- 七 3.5.2@click="addArticle('草稿')"4.3.2 ;title==='添加文章'? addArticle('草稿'):updateArticle('草稿')-->
  311. </el-form-item>
  312. </el-form-item>
  313. </el-form>
  314. </el-drawer>
  315. </el-card>
  316. </template>
  317. <style lang="scss" scoped>
  318. .page-container {
  319. min-height: 100%;
  320. box-sizing: border-box;
  321. .header {
  322. display: flex;
  323. align-items: center;
  324. justify-content: space-between;
  325. }
  326. }
  327. /*3.1 抽屉样式 */
  328. .avatar-uploader {
  329. :deep() {
  330. .avatar {
  331. width: 178px;
  332. height: 178px;
  333. display: block;
  334. }
  335. .el-upload {
  336. border: 1px dashed var(--el-border-color);
  337. border-radius: 6px;
  338. cursor: pointer;
  339. position: relative;
  340. overflow: hidden;
  341. transition: var(--el-transition-duration-fast);
  342. }
  343. .el-upload:hover {
  344. border-color: var(--el-color-primary);
  345. }
  346. .el-icon.avatar-uploader-icon {
  347. font-size: 28px;
  348. color: #8c939d;
  349. width: 178px;
  350. height: 178px;
  351. text-align: center;
  352. }
  353. }
  354. }
  355. .editor {
  356. width: 100%;
  357. :deep(.ql-editor) {
  358. min-height: 200px;
  359. }
  360. }
  361. //3.3.4 样式
  362. .editor {
  363. width: 100%;
  364. :deep(.ql-editor) {
  365. min-height: 200px;
  366. }
  367. }
  368. </style>

八、顶部导航栏信息展示

在Layout.vue中,页面加载完就发送请求,获取个人信息展示,并存储到pinia中,因为将来在个人中心中修改信息的时候还需要使用

1、 user.js中提供获取个人信息的函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 二 注册函数 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }
  12. // 三 登录函数 提供调用登录接口的函数
  13. export const userLoginService = (loginData)=>{
  14. //借助于URLSearchParam完成参数传递
  15. const params = new URLSearchParams();
  16. for(let key in loginData){
  17. params.append(key,loginData[key]);
  18. }
  19. return request.post('/user/login',params);
  20. }
  21. //1获取个人信息
  22. export const userInfoGetService = ()=>{
  23. return request.get('/user/userInfo');
  24. }

2、 src/stores/userInfo.js中,定义个人中心状态

  1. import {defineStore} from 'pinia'
  2. import {ref} from 'vue'
  3. const useUserInfoStore = defineStore('userInfo',()=>{
  4. //定义状态相关的内容
  5. const info = ref({})
  6. const setInfo = (newInfo)=>{
  7. info.value = newInfo
  8. }
  9. const removeInfo = ()=>{
  10. info.value = {}
  11. }
  12. return {info,setInfo,removeInfo}
  13. },{persist:true})
  14. export default useUserInfoStore;

3、 Layout.vue中获取个人信息,并存储到pinia中

  1. import {ref} from 'vue'
  2. //导入接口函数
  3. import { userInfoGetService } from '@/api/user.js'
  4. //导入pinia
  5. import useUserInfoStore from '@/stores/userInfo.js'
  6. const userInfoStore = useUserInfoStore();
  7. //获取个人信息
  8. const getUserInfo = async ()=>{
  9. let result = await userInfoGetService();
  10. //存储pinia
  11. userInfoStore.info =result.data;
  12. }
  13. getUserInfo()

4、Layout.vue的顶部导航栏中,展示昵称和头像

 <div>编码集中营:<strong>{{ userInfoStore.info.nickname ? userInfoStore.info.nickname : userInfoStore.info.usrename }}</strong></div>
 <el-avatar :src="userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar" />
​全部Layout.vue
  1. <script setup>
  2. import {
  3. Management,
  4. Promotion,
  5. UserFilled,
  6. User,
  7. Crop,
  8. EditPen,
  9. SwitchButton,
  10. CaretBottom
  11. } from '@element-plus/icons-vue'
  12. import avatar from '@/assets/default.png'
  13. // =======3 个人用户信息
  14. import {ref} from 'vue'
  15. //导入接口函数
  16. import { userInfoGetService } from '@/api/user.js'
  17. //导入pinia
  18. import useUserInfoStore from '@/stores/userInfo.js'
  19. const userInfoStore = useUserInfoStore();
  20. //获取个人信息
  21. const getUserInfo = async ()=>{
  22. let result = await userInfoGetService();
  23. //存储pinia
  24. userInfoStore.info =result.data;
  25. }
  26. getUserInfo()
  27. </script>
  28. <template>
  29. <!-- element-plus 中的容器 -->
  30. <el-container class="layout-container">
  31. <!-- 左侧菜单 -->
  32. <el-aside width="200px">
  33. <div class="el-aside__logo"></div>
  34. <!-- element-plus 菜单标签 -->
  35. <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
  36. router>
  37. <el-menu-item index="/article/category"> <!-- 五 3.3 -->
  38. <el-icon>
  39. <Management />
  40. </el-icon>
  41. <span>文章分类</span>
  42. </el-menu-item>
  43. <el-menu-item index="/article/manage"> <!-- 五 3.3 -->
  44. <el-icon>
  45. <Promotion />
  46. </el-icon>
  47. <span>文章管理</span>
  48. </el-menu-item>
  49. <el-sub-menu >
  50. <template #title>
  51. <el-icon>
  52. <UserFilled />
  53. </el-icon>
  54. <span>个人中心</span>
  55. </template>
  56. <el-menu-item index="/user/info"> <!-- 五 3.3 -->
  57. <el-icon>
  58. <User />
  59. </el-icon>
  60. <span>基本资料</span>
  61. </el-menu-item>
  62. <el-menu-item index="/user/avatar"> <!-- 五 3.3 -->
  63. <el-icon>
  64. <Crop />
  65. </el-icon>
  66. <span>更换头像</span>
  67. </el-menu-item>
  68. <el-menu-item index="/user/resetPassword"> <!-- 五 3.3 -->
  69. <el-icon>
  70. <EditPen />
  71. </el-icon>
  72. <span>重置密码</span>
  73. </el-menu-item>
  74. </el-sub-menu>
  75. </el-menu>
  76. </el-aside>
  77. <!-- 右侧主区域 -->
  78. <el-container>
  79. <!-- 头部区域 -->
  80. <el-header>
  81. <div>编码集中营:<strong>{{ userInfoStore.info.nickname ? userInfoStore.info.nickname : userInfoStore.info.usrename }}</strong></div> <!-- 八 4 {{ userInfoStore.info.nickname ? userInfoStore.info.nickname : userInfoStore.info.usrename }}-->
  82. <el-dropdown placement="bottom-end">
  83. <span class="el-dropdown__box">
  84. <el-avatar :src="userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar" /> <!-- 八 4 userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar-->
  85. <el-icon>
  86. <CaretBottom />
  87. </el-icon>
  88. </span>
  89. <template #dropdown>
  90. <el-dropdown-menu>
  91. <el-dropdown-item command="profile" :icon="User">基本资料</el-dropdown-item>
  92. <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
  93. <el-dropdown-item command="password" :icon="EditPen">重置密码</el-dropdown-item>
  94. <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
  95. </el-dropdown-menu>
  96. </template>
  97. </el-dropdown>
  98. </el-header>
  99. <!-- 中间区域 -->
  100. <el-main>
  101. <!-- 五 3.3 -->
  102. <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
  103. 内容展示区
  104. </div> -->
  105. <router-view></router-view>
  106. </el-main>
  107. <!-- 底部区域 -->
  108. <el-footer>国际大事件 ©2023 Created by 春天的菠菜</el-footer>
  109. </el-container>
  110. </el-container>
  111. </template>
  112. <style lang="scss" scoped>
  113. .layout-container {
  114. height: 100vh;
  115. .el-aside {
  116. background-color: #232323;
  117. &__logo {
  118. height: 120px;
  119. background: url('@/assets/logo.png') no-repeat center / 120px auto;
  120. }
  121. .el-menu {
  122. border-right: none;
  123. }
  124. }
  125. .el-header {
  126. background-color: #fff;
  127. display: flex;
  128. align-items: center;
  129. justify-content: space-between;
  130. .el-dropdown__box {
  131. display: flex;
  132. align-items: center;
  133. .el-icon {
  134. color: #999;
  135. margin-left: 10px;
  136. }
  137. &:active,
  138. &:focus {
  139. outline: none;
  140. }
  141. }
  142. }
  143. .el-footer {
  144. display: flex;
  145. align-items: center;
  146. justify-content: center;
  147. font-size: 14px;
  148. color: #666;
  149. }
  150. }
  151. </style>

九 、页面右上角下拉菜单el-dropdown中功能实现

在el-dropdown中有四个子条目,分别是:

  • 基本资料

  • 更换头像

  • 重置密码

  • 退出登录

其中其三个起到路由功能,跟左侧菜单中【个人中心】下面的二级菜单是同样的功能,退出登录需要删除本地pinia中存储的token以及userInfo

1、路由实现:

在el-dropdown-item标签上添加command属性,属性值和路由表中/user/xxx保持一致

  1. <!-- 下拉菜单-->
  2. <!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
  3. <el-dropdown placement="bottom-end" @command="handleCommand">
  4. <span class="el-dropdown__box">
  5. <el-avatar :src="userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar" /> <!-- 八 4 userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar-->
  6. <el-icon>
  7. <CaretBottom />
  8. </el-icon>
  9. </span>
  10. <template #dropdown>
  11. <el-dropdown-menu>
  12. <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
  13. <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
  14. <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
  15. <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
  16. </el-dropdown-menu>
  17. </template>
  18. </el-dropdown>

在el-dropdown标签上绑定command事件,当有条目被点击后,会触发这个事件

<el-dropdown placement="bottom-end" @command="handleCommand">

提供handleCommand函数,参数为点击条目的command属性值

  1. //dropDown条目被点击后,回调的函数
  2. import {useRouter} from 'vue-router'
  3. const router = useRouter()
  4. const handleCommand = (command)=>{
  5.     if(command==='logout'){
  6.         //退出登录
  7.         alert('退出登录')
  8.     }else{
  9.         //路由
  10.         router.push('/user/'+command)
  11.     }
  12. }

2、 退出登录实现:

  1. <script setup>
  2. import {
  3. Management,
  4. Promotion,
  5. UserFilled,
  6. User,
  7. Crop,
  8. EditPen,
  9. SwitchButton,
  10. CaretBottom
  11. } from '@element-plus/icons-vue'
  12. import avatar from '@/assets/default.png'
  13. //1
  14. //dropDown条目被点击后,回调的函数
  15. import {useRouter} from 'vue-router'
  16. //2
  17. import {ElMessage,ElMessageBox} from 'element-plus'
  18. import { useTokenStore } from '@/stores/token.js'
  19. // =======3 个人用户信息
  20. import {ref} from 'vue'
  21. //导入接口函数
  22. import { userInfoGetService } from '@/api/user.js'
  23. //导入pinia
  24. import useUserInfoStore from '@/stores/userInfo.js'
  25. const userInfoStore = useUserInfoStore();
  26. //获取个人信息
  27. const getUserInfo = async ()=>{
  28. let result = await userInfoGetService();
  29. //存储pinia
  30. userInfoStore.info =result.data;
  31. }
  32. getUserInfo()
  33. //2
  34. const tokenStore = useTokenStore()
  35. //1
  36. const router = useRouter()
  37. const handleCommand = (command)=>{
  38. //判断指令
  39. if(command === 'logout'){
  40. //退出登录
  41. ElMessageBox.confirm(
  42. '您确认要退出吗?',
  43. '温馨提示',
  44. {
  45. confirmButtonText: '确认',
  46. cancelButtonText: '取消',
  47. type: 'warning',
  48. }
  49. )
  50. .then(async () => {
  51. //退出登录
  52. //1.清空pinia中存储的token以及个人信息
  53. tokenStore.removeToken()
  54. userInfoStore.removeInfo()
  55. //2.跳转到登录页面
  56. router.push('/login')
  57. ElMessage({
  58. type: 'success',
  59. message: '退出登录成功',
  60. })
  61. })
  62. .catch(() => {
  63. ElMessage({
  64. type: 'info',
  65. message: '用户取消了退出登录',
  66. })
  67. })
  68. }else{
  69. //路由
  70. router.push('/user/'+command)
  71. }
  72. }
  73. </script>
  74. <template>
  75. <!-- element-plus 中的容器 -->
  76. <el-container class="layout-container">
  77. <!-- 左侧菜单 -->
  78. <el-aside width="200px">
  79. <div class="el-aside__logo"></div>
  80. <!-- element-plus 菜单标签 -->
  81. <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff"
  82. router>
  83. <el-menu-item index="/article/category"> <!-- 五 3.3 -->
  84. <el-icon>
  85. <Management />
  86. </el-icon>
  87. <span>文章分类</span>
  88. </el-menu-item>
  89. <el-menu-item index="/article/manage"> <!-- 五 3.3 -->
  90. <el-icon>
  91. <Promotion />
  92. </el-icon>
  93. <span>文章管理</span>
  94. </el-menu-item>
  95. <el-sub-menu >
  96. <template #title>
  97. <el-icon>
  98. <UserFilled />
  99. </el-icon>
  100. <span>个人中心</span>
  101. </template>
  102. <el-menu-item index="/user/info"> <!-- 五 3.3 -->
  103. <el-icon>
  104. <User />
  105. </el-icon>
  106. <span>基本资料</span>
  107. </el-menu-item>
  108. <el-menu-item index="/user/avatar"> <!-- 五 3.3 -->
  109. <el-icon>
  110. <Crop />
  111. </el-icon>
  112. <span>更换头像</span>
  113. </el-menu-item>
  114. <el-menu-item index="/user/resetPassword"> <!-- 五 3.3 -->
  115. <el-icon>
  116. <EditPen />
  117. </el-icon>
  118. <span>重置密码</span>
  119. </el-menu-item>
  120. </el-sub-menu>
  121. </el-menu>
  122. </el-aside>
  123. <!-- 右侧主区域 -->
  124. <el-container>
  125. <!-- 头部区域 -->
  126. <el-header>
  127. <div>编码集中营:<strong>{{ userInfoStore.info.nickname ? userInfoStore.info.nickname : userInfoStore.info.usrename }}</strong></div> <!-- 八 4 {{ userInfoStore.info.nickname ? userInfoStore.info.nickname : userInfoStore.info.usrename }}-->
  128. <!-- 下拉菜单-->
  129. <!-- command: 条目被点击后会触发,在事件函数上可以声明一个参数,接收条目对应的指令 -->
  130. <el-dropdown placement="bottom-end" @command="handleCommand">
  131. <span class="el-dropdown__box">
  132. <el-avatar :src="userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar" /> <!-- 八 4 userInfoStore.info.userPic ? userInfoStore.info.userPic : avatar-->
  133. <el-icon>
  134. <CaretBottom />
  135. </el-icon>
  136. </span>
  137. <template #dropdown>
  138. <el-dropdown-menu>
  139. <el-dropdown-item command="info" :icon="User">基本资料</el-dropdown-item>
  140. <el-dropdown-item command="avatar" :icon="Crop">更换头像</el-dropdown-item>
  141. <el-dropdown-item command="resetPassword" :icon="EditPen">重置密码</el-dropdown-item>
  142. <el-dropdown-item command="logout" :icon="SwitchButton">退出登录</el-dropdown-item>
  143. </el-dropdown-menu>
  144. </template>
  145. </el-dropdown>
  146. </el-header>
  147. <!-- 中间区域 -->
  148. <el-main>
  149. <!-- 五 3.3 -->
  150. <!-- <div style="width: 1290px; height: 570px;border: 1px solid red;">
  151. 内容展示区
  152. </div> -->
  153. <router-view></router-view>
  154. </el-main>
  155. <!-- 底部区域 -->
  156. <el-footer>国际大事件 ©2023 Created by 春天的菠菜</el-footer>
  157. </el-container>
  158. </el-container>
  159. </template>
  160. <style lang="scss" scoped>
  161. .layout-container {
  162. height: 100vh;
  163. .el-aside {
  164. background-color: #232323;
  165. &__logo {
  166. height: 120px;
  167. background: url('@/assets/logo.png') no-repeat center / 120px auto;
  168. }
  169. .el-menu {
  170. border-right: none;
  171. }
  172. }
  173. .el-header {
  174. background-color: #fff;
  175. display: flex;
  176. align-items: center;
  177. justify-content: space-between;
  178. .el-dropdown__box {
  179. display: flex;
  180. align-items: center;
  181. .el-icon {
  182. color: #999;
  183. margin-left: 10px;
  184. }
  185. &:active,
  186. &:focus {
  187. outline: none;
  188. }
  189. }
  190. }
  191. .el-footer {
  192. display: flex;
  193. align-items: center;
  194. justify-content: center;
  195. font-size: 14px;
  196. color: #666;
  197. }
  198. }
  199. </style>

十、基本资料修改

1、 基本资料页面组件UserInfo.vue

views\user\UserInfo.vue
  1. <script setup>
  2. import { ref } from 'vue'
  3. const userInfo = ref({
  4. id: 0,
  5. username: 'zhangsan',
  6. nickname: 'zs',
  7. email: 'zs@163.com',
  8. })
  9. const rules = {
  10. nickname: [
  11. { required: true, message: '请输入用户昵称', trigger: 'blur' },
  12. {
  13. pattern: /^\S{2,10}$/,
  14. message: '昵称必须是2-10位的非空字符串',
  15. trigger: 'blur'
  16. }
  17. ],
  18. email: [
  19. { required: true, message: '请输入用户邮箱', trigger: 'blur' },
  20. { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  21. ]
  22. }
  23. </script>
  24. <template>
  25. <el-card class="page-container">
  26. <template #header>
  27. <div class="header">
  28. <span>基本资料</span>
  29. </div>
  30. </template>
  31. <el-row>
  32. <el-col :span="12">
  33. <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
  34. <el-form-item label="登录名称">
  35. <el-input v-model="userInfo.username" disabled></el-input>
  36. </el-form-item>
  37. <el-form-item label="用户昵称" prop="nickname">
  38. <el-input v-model="userInfo.nickname"></el-input>
  39. </el-form-item>
  40. <el-form-item label="用户邮箱" prop="email">
  41. <el-input v-model="userInfo.email"></el-input>
  42. </el-form-item>
  43. <el-form-item>
  44. <el-button type="primary">提交修改</el-button>
  45. </el-form-item>
  46. </el-form>
  47. </el-col>
  48. </el-row>
  49. </el-card>
  50. </template>

2、 表单数据回显

个人信息之前已经存储到了pinia中,只需要从pinia中获取个人信息,替换模板数据即可

  1. //2
  2. import useUserInfoStore from '@/stores/userInfo.js';
  3. const userInfoStore = useUserInfoStore()
  4. const userInfo = ref({...userInfoStore.info})

3、 接口调用

在src/api/user.js中提供修改基本资料的函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 二 注册函数 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }
  12. // 三 登录函数 提供调用登录接口的函数
  13. export const userLoginService = (loginData)=>{
  14. //借助于URLSearchParam完成参数传递
  15. const params = new URLSearchParams();
  16. for(let key in loginData){
  17. params.append(key,loginData[key]);
  18. }
  19. return request.post('/user/login',params);
  20. }
  21. //1获取个人信息
  22. export const userInfoGetService = ()=>{
  23. return request.get('/user/userInfo');
  24. }
  25. //3 修改个人信息
  26. export const userInfoUpdateService = (userInfo)=>{
  27. return request.put('/user/update',userInfo)
  28. }

为修改按钮绑定单击事件

<el-button type="primary" @click="updateUserInfo">提交修改</el-button> <!-- 十  3  @click="updateUserInfo"-->

提供updateUserInfo函数

  1. const updateUserInfo = async ()=>{
  2. let result = await userInfoUpdateService(userInfo.value)
  3. ElMessage.success(result.message? result.message:'修改成功')
  4. //更新pinia中的数据
  5. userInfoStore.info.nickname=userInfo.value.nickname
  6. userInfoStore.info.email = userInfo.value.email
  7. }
  1. <script setup>
  2. import { ref } from 'vue'
  3. //3
  4. import { ElMessage } from 'element-plus';
  5. import { userInfoUpdateService } from '@/api/user.js';
  6. //2
  7. import useUserInfoStore from '@/stores/userInfo.js';
  8. const userInfoStore = useUserInfoStore()
  9. const userInfo = ref({...userInfoStore.info})
  10. const rules = {
  11. nickname: [
  12. { required: true, message: '请输入用户昵称', trigger: 'blur' },
  13. {
  14. pattern: /^\S{2,10}$/,
  15. message: '昵称必须是2-10位的非空字符串',
  16. trigger: 'blur'
  17. }
  18. ],
  19. email: [
  20. { required: true, message: '请输入用户邮箱', trigger: 'blur' },
  21. { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  22. ]
  23. }
  24. //3
  25. const updateUserInfo = async ()=>{
  26. let result = await userInfoUpdateService(userInfo.value)
  27. ElMessage.success(result.message? result.message:'修改成功')
  28. //更新pinia中的数据
  29. userInfoStore.info.nickname=userInfo.value.nickname
  30. userInfoStore.info.email = userInfo.value.email
  31. }
  32. </script>
  33. <template>
  34. <el-card class="page-container">
  35. <template #header>
  36. <div class="header">
  37. <span>基本资料</span>
  38. </div>
  39. </template>
  40. <el-row>
  41. <el-col :span="12">
  42. <el-form :model="userInfo" :rules="rules" label-width="100px" size="large">
  43. <el-form-item label="登录名称">
  44. <el-input v-model="userInfo.username" disabled></el-input>
  45. </el-form-item>
  46. <el-form-item label="用户昵称" prop="nickname">
  47. <el-input v-model="userInfo.nickname"></el-input>
  48. </el-form-item>
  49. <el-form-item label="用户邮箱" prop="email">
  50. <el-input v-model="userInfo.email"></el-input>
  51. </el-form-item>
  52. <el-form-item>
  53. <el-button type="primary" @click="updateUserInfo">提交修改</el-button> <!-- 十 3 @click="updateUserInfo"-->
  54. </el-form-item>
  55. </el-form>
  56. </el-col>
  57. </el-row>
  58. </el-card>
  59. </template>

十一、修改头像

1、 修改头像页面组件UserAvatar.vue

  1. <script setup>
  2. import { Plus, Upload } from '@element-plus/icons-vue'
  3. import {ref} from 'vue'
  4. import avatar from '@/assets/default.png'
  5. const uploadRef = ref()
  6. //用户头像地址
  7. const imgUrl= avatar
  8. </script>
  9. <template>
  10. <el-card class="page-container">
  11. <template #header>
  12. <div class="header">
  13. <span>更换头像</span>
  14. </div>
  15. </template>
  16. <el-row>
  17. <el-col :span="12">
  18. <el-upload
  19. ref="uploadRef"
  20. class="avatar-uploader"
  21. :show-file-list="false"
  22. >
  23. <img v-if="imgUrl" :src="imgUrl" class="avatar" />
  24. <img v-else src="avatar" width="278" />
  25. </el-upload>
  26. <br />
  27. <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">
  28. 选择图片
  29. </el-button>
  30. <el-button type="success" :icon="Upload" size="large">
  31. 上传头像
  32. </el-button>
  33. </el-col>
  34. </el-row>
  35. </el-card>
  36. </template>
  37. <style lang="scss" scoped>
  38. .avatar-uploader {
  39. :deep() {
  40. .avatar {
  41. width: 278px;
  42. height: 278px;
  43. display: block;
  44. }
  45. .el-upload {
  46. border: 1px dashed var(--el-border-color);
  47. border-radius: 6px;
  48. cursor: pointer;
  49. position: relative;
  50. overflow: hidden;
  51. transition: var(--el-transition-duration-fast);
  52. }
  53. .el-upload:hover {
  54. border-color: var(--el-color-primary);
  55. }
  56. .el-icon.avatar-uploader-icon {
  57. font-size: 28px;
  58. color: #8c939d;
  59. width: 278px;
  60. height: 278px;
  61. text-align: center;
  62. }
  63. }
  64. }
  65. </style>

2、 头像回显

从pinia中读取用户的头像数据

  1. //读取用户信息
  2. import {ref} from 'vue'
  3. import useUserInfoStore from '@/stores/userInfo.js'
  4. const userInfoStore = useUserInfoStore()
  5. //用户头像地址
  6. const imgUrl=ref(userInfoStore.info.userPic)

img标签上绑定图片地址

  1. <img v-if="imgUrl" :src="imgUrl" class="avatar" />
  2. <img v-else :src="avatar" width="278" />

3、 头像上传

为el-upload指定属性值,分别有:

  • action: 服务器接口路径

  • headers: 设置请求头,需要携带token

  • on-success: 上传成功的回调函数

  • name: 上传图片的字段名称

  1. <el-upload
  2. ref="uploadRef"
  3. class="avatar-uploader"
  4. :show-file-list="false"
  5. :auto-upload="true"
  6. action="/api/upload"
  7. name="file"
  8. :headers="{Authorization:tokenStore.token}"
  9. :on-success="uploadSuccess"
  10. >
  11. <img v-if="imgUrl" :src="imgUrl" class="avatar" />
  12. <img v-else src="avatar" width="278" />
  13. </el-upload>

提供上传成功的回调函数

  1. //读取token信息
  2. import {useTokenStore} from '@/stores/token.js'
  3. const tokenStore = useTokenStore()
  4. //图片上传成功的回调
  5. const uploadSuccess = (result)=>{
  6.    //回显图片
  7.    imgUrl.value = result.data
  8. }

外部触发图片选择

需要获取到el-upload组件,然后再通过$el.querySelector('input')获取到el-upload对应的元素,触发click事件

  1. // 十 、3//获取el-upload元素
  2. const uploadRef = ref()
  1. <el-button type="primary" :icon="Plus" size="large"  @click="uploadRef.$el.querySelector('input').click()">
  2.   选择图片
  3. </el-button>

4、 上传头像接口调用

在user.js中提供修改头像的函数

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 二 注册函数 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }
  12. // 三 登录函数 提供调用登录接口的函数
  13. export const userLoginService = (loginData)=>{
  14. //借助于URLSearchParam完成参数传递
  15. const params = new URLSearchParams();
  16. for(let key in loginData){
  17. params.append(key,loginData[key]);
  18. }
  19. return request.post('/user/login',params);
  20. }
  21. //1获取个人信息
  22. export const userInfoGetService = ()=>{
  23. return request.get('/user/userInfo');
  24. }
  25. //3 修改个人信息
  26. export const userInfoUpdateService = (userInfo)=>{
  27. return request.put('/user/update',userInfo)
  28. }
  29. //4 修改头像
  30. export const userAvatarUpdateService=(avatarUrl)=>{
  31. let params = new URLSearchParams();
  32. params.append('avatarUrl',avatarUrl)
  33. return request.patch('/user/updateAvatar',params)
  34. }

为【上传头像】按钮绑定单击事件

  1. <el-button type="success" :icon="Upload" size="large" @click="updateAvatar"> <!-- 十 4 @click="updateAvatar"-->
  2. 上传头像
  3. </el-button>

提供updateAvatar函数,完成头像更新

//调用接口,更新头像url
import {userAvatarUpdateService} from '@/api/user.js'
import {ElMessage} from 'element-plus'
const updateAvatar = async ()=>{
    let result = await userAvatarUpdateService(imgUrl.value)
    ElMessage.success(result.message? result.message:'修改成功')
    //更新pinia中的数据
    userInfoStore.info.userPic=imgUrl.value
}
  1. <script setup>
  2. import { Plus, Upload } from '@element-plus/icons-vue'
  3. import avatar from '@/assets/default.png'
  4. //3
  5. import { useTokenStore } from '@/stores/token.js'
  6. //4调用接口,更新头像url
  7. import {userAvatarUpdateService} from '@/api/user.js'
  8. import {ElMessage} from 'element-plus'
  9. //2
  10. //读取用户信息
  11. import {ref} from 'vue'
  12. import useUserInfoStore from '@/stores/userInfo.js'
  13. const userInfoStore = useUserInfoStore()
  14. //用户头像地址
  15. const imgUrl=ref(userInfoStore.info.userPic)
  16. //3
  17. const tokenStore = useTokenStore();
  18. //图片上传成功的回调
  19. const uploadSuccess = (result)=>{
  20. //回显图片
  21. imgUrl.value = result.data
  22. }
  23. // 十 、3//获取el-upload元素
  24. const uploadRef = ref()
  25. //4
  26. const updateAvatar = async ()=>{
  27. let result = await userAvatarUpdateService(imgUrl.value)
  28. ElMessage.success(result.message? result.message:'修改成功')
  29. //更新pinia中的数据
  30. userInfoStore.info.userPic=imgUrl.value
  31. }
  32. </script>
  33. <template>
  34. <el-card class="page-container">
  35. <template #header>
  36. <div class="header">
  37. <span>更换头像</span>
  38. </div>
  39. </template>
  40. <el-row>
  41. <el-col :span="12">
  42. <!--
  43. auto-upload:是否自动上传
  44. action: 服务器接口路径
  45. name: 上传的文件字段名
  46. headers: 设置上传的请求头
  47. on-success: 上传成功的回调函数
  48. -->
  49. <el-upload
  50. ref="uploadRef"
  51. class="avatar-uploader"
  52. :show-file-list="false"
  53. :auto-upload="true"
  54. action="/api/upload"
  55. name="file"
  56. :headers="{Authorization:tokenStore.token}"
  57. :on-success="uploadSuccess"
  58. >
  59. <img v-if="imgUrl" :src="imgUrl" class="avatar" />
  60. <img v-else :src="avatar" width="278" />
  61. </el-upload>
  62. <br />
  63. <el-button type="primary" :icon="Plus" size="large" @click="uploadRef.$el.querySelector('input').click()">
  64. 选择图片
  65. </el-button>
  66. <el-button type="success" :icon="Upload" size="large" @click="updateAvatar"> <!-- 十 4 @click="updateAvatar"-->
  67. 上传头像
  68. </el-button>
  69. </el-col>
  70. </el-row>
  71. </el-card>
  72. </template>
  73. <style lang="scss" scoped>
  74. .avatar-uploader {
  75. :deep() {
  76. .avatar {
  77. width: 278px;
  78. height: 278px;
  79. display: block;
  80. }
  81. .el-upload {
  82. border: 1px dashed var(--el-border-color);
  83. border-radius: 6px;
  84. cursor: pointer;
  85. position: relative;
  86. overflow: hidden;
  87. transition: var(--el-transition-duration-fast);
  88. }
  89. .el-upload:hover {
  90. border-color: var(--el-color-primary);
  91. }
  92. .el-icon.avatar-uploader-icon {
  93. font-size: 28px;
  94. color: #8c939d;
  95. width: 278px;
  96. height: 278px;
  97. text-align: center;
  98. }
  99. }
  100. }
  101. </style>

十二、 重置密码

1、user.js 重置密码

  1. //导入request.js请求工具
  2. import request from '@/utils/request.js'
  3. // 二 注册函数 提供调用注册接口的函数
  4. export const userRegisterService = (registerData) =>{
  5. //借助于URLSearchParam完成参数传递
  6. const params = new URLSearchParams();
  7. for(let key in registerData){
  8. params.append(key,registerData[key]);
  9. }
  10. return request.post('/user/register',params);
  11. }
  12. // 三 登录函数 提供调用登录接口的函数
  13. export const userLoginService = (loginData)=>{
  14. //借助于URLSearchParam完成参数传递
  15. const params = new URLSearchParams();
  16. for(let key in loginData){
  17. params.append(key,loginData[key]);
  18. }
  19. return request.post('/user/login',params);
  20. }
  21. //1获取个人信息
  22. export const userInfoGetService = ()=>{
  23. return request.get('/user/userInfo');
  24. }
  25. //3 修改个人信息
  26. export const userInfoUpdateService = (userInfo)=>{
  27. return request.put('/user/update',userInfo)
  28. }
  29. // 十一 4 修改头像
  30. export const userAvatarUpdateService=(avatarUrl)=>{
  31. let params = new URLSearchParams();
  32. params.append('avatarUrl',avatarUrl)
  33. return request.patch('/user/updateAvatar',params)
  34. }
  35. // 十二 重置密码
  36. export const userUpdatePwdService=(userPwd)=>{
  37. return request.patch('/user/updatePwd',userPwd)
  38. }

 2、UserResetPassword.vue

 views/UserResetPassword.vue

  1. <script setup>
  2. import { ElMessage } from 'element-plus';
  3. import { useTokenStore } from '@/stores/token.js'
  4. import { ref } from 'vue'
  5. import { userUpdatePwdService } from '@/api/user.js';
  6. import {useRouter} from 'vue-router'
  7. const router = useRouter()
  8. const userPwd = ref({
  9. old_pwd: '',
  10. new_pwd: '',
  11. re_pwd: '',
  12. })
  13. const tokenStore = useTokenStore()
  14. const updateUserPwd = async ()=>{
  15. let result = await userUpdatePwdService(userPwd.value)
  16. // ElMessage.success(result.message? result.message:'修改成功')
  17. //退出登录
  18. //1.清空pinia中存储的token(pinia中个人信息没有存储密码信息,所以不处理)
  19. tokenStore.removeToken()
  20. //2.跳转到登录页面
  21. router.push('/login')
  22. ElMessage({
  23. type: 'success',
  24. message: '修改密码成功,请重新成功',
  25. })
  26. }
  27. const rules = {
  28. old_pwd: [
  29. { required: true, message: '请输入原始密码', trigger: 'blur' },
  30. {
  31. pattern: /^\S{5,16}$/,
  32. message: '原始密码必须是5-16位的非空字符串',
  33. trigger: 'blur'
  34. }
  35. ],
  36. new_pwd: [
  37. { required: true, message: '请输入新密码', trigger: 'blur' },
  38. {
  39. pattern: /^\S{5,16}$/,
  40. message: '新密码必须是5-16位的非空字符串',
  41. trigger: 'blur'
  42. }
  43. ],
  44. re_pwd: [
  45. { required: true, message: '请输入确认密码', trigger: 'blur' },
  46. {
  47. pattern: /^\S{5,16}$/,
  48. message: '确认密码必须是5-16位的非空字符串',
  49. trigger: 'blur'
  50. }
  51. ]
  52. }
  53. </script>
  54. <template>
  55. <el-card class="page-container">
  56. <template #header>
  57. <div class="header">
  58. <span>重置密码</span>
  59. </div>
  60. </template>
  61. <el-row>
  62. <el-col :span="12">
  63. <el-form :model="userPwd" :rules="rules" label-width="100px" size="large">
  64. <el-form-item label="原密码" prop="old_pwd">
  65. <el-input type="password" v-model="userPwd.old_pwd"></el-input>
  66. </el-form-item>
  67. <el-form-item label="新密码" prop="new_pwd">
  68. <el-input type="password" v-model="userPwd.new_pwd"></el-input>
  69. </el-form-item>
  70. <el-form-item label="确认密码" prop="re_pwd">
  71. <el-input type="password" v-model="userPwd.re_pwd"></el-input>
  72. </el-form-item>
  73. <el-form-item>
  74. <el-button type="primary" @click="updateUserPwd">提交修改</el-button>
  75. </el-form-item>
  76. </el-form>
  77. </el-col>
  78. </el-row>
  79. </el-card>
  80. </template>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/567677
推荐阅读
相关标签
  

闽ICP备14008679号