JAVAWeb实战(前端篇)

项目实战一

0.项目结构

1.创建vue3项目,并导入所需的依赖

npm install vue-router
npm install axios
npm install pinia
npm install vue

2.定义路由,axios,pinia相关的对象 文件(.js)

2.1路由(.js)

import {createRouter,createWebHashHistory} from 'vue-router'import Login from '../components/Login.vue'
import Regist from '../components/Regist.vue'
import ShowSchedule from '../components/ShowSchedule.vue'import pinia from '../pinia.js'
import {defineUser} from '../store/userStore.js'let sysUser = defineUser(pinia)
const router= createRouter({history:createWebHashHistory(),routes:[{path:"/",redirect:"/showSchedule"},{path:"/showSchedule",component:ShowSchedule},{path:"/login",component:Login},{path:"/regist",component:Regist}]
})// 路由 的全局前置守卫 判断是否可以访问showSchedule
router.beforeEach((to,from,next)=>{if(to.path == '/showSchedule'){// 登陆过放行// 没登录 回到登录页if(sysUser.username == ''){next("/login")}else{next()}}else{next()}})export default router 

2.2axios(.js)

import axios from 'axios'//  创建instance实例
const instance = axios.create({baseURL:'http://localhost:8080/'})//  添加请求拦截
instance.interceptors.request.use(// 设置请求头配置信息config=>{//处理指定的请求头return config},// 设置请求错误处理函数error=>{return Promise.reject(error)}
)
// 添加响应拦截器
instance.interceptors.response.use(// 设置响应正确时的处理函数response=>{return response},// 设置响应异常时的处理函数error=>{return Promise.reject(error)}
)
// 默认导出
export default instance

2.3pinia

2.3.1开启pinia(.js)
// 开启pinia
import {createPinia} from 'pinia'
let pinia = createPinia()export default pinia
2.3.2根据数据库定义接收的pinia文件(.js)

数据库

schedule表

对应的pinia文件

这里用集合来接收所有数据

/* 
专门用于存储日程状态信息的pinia*/
import {defineStore} from 'pinia'export const defindSchedule= defineStore("scheduleList",{state:()=>{return {itemList:[]}},getters:{},actions:{}}

user表

对应的pinia文件

/* 
专门用于存储用户状态信息的pinia*/
import {defineStore} from 'pinia'export const defineUser= defineStore("loginUser",{state:()=>{return {uid:0,username:'' }},getters:{},actions:{}}
)

将他们挂载在main.js文件中

import { createApp } from 'vue'import App from './App.vue'import router from './router/router'import pinia from './pinia.js'const app =createApp(App)
app.use(router)
app.use(pinia)
app.mount('#app')

3.定义组件

3.1定义头组件

Header.vue

<script setup>/* 导入pinia数据 */import {defineUser} from "../store/userStore.js"import {defindSchedule} from "../store/scheduleStore.js"let sysUser = defineUser()let schedule = defindSchedule()import {useRouter} from 'vue-router'let router = useRouter()function logout(){// 清除所有pinia数据sysUser.$reset()schedule.$reset()// 跳转到登录页router.push("/login")}</script><template><div><h1 class="ht">欢迎使用日程管理系统</h1><div><div  class="optionDiv" v-if="sysUser.username == ''"><router-link to="/login"><button class="b1s">登录</button></router-link>   <router-link to="/regist"><button class="b1s">注册</button></router-link></div><div   class="optionDiv" v-else>欢迎 {{ sysUser.username }}   <button class="b1b" @click="logout()">退出登录</button> <router-link to="/showSchedule"><button class="b1b">查看我的日程</button></router-link></div><br></div></div>
</template><style scoped>.ht{text-align: center;color: cadetblue;font-family: 幼圆;}.b1s{border: 2px solid powderblue;border-radius: 4px;width:60px;background-color: antiquewhite;}.b1b{border: 2px solid powderblue;border-radius: 4px;width:100px;background-color: antiquewhite;}.optionDiv{width: 400px;float: right;}
</style>

3.2定义登入组件  Login.vue

<script setup>import {ref,reactive} from 'vue'import {useRouter} from 'vue-router'const router = useRouter()import{ defineUser}  from '../store/userStore.js'let sysUser = defineUser()import request  from '../utils/request'let loginUser =reactive({username:"",userPwd:""})let usernameMsg =ref("")let userPwdMsg =ref("")function checkUsername(){let usernameReg= /^[a-zA-Z0-9]{5,10}$/if(!usernameReg.test(loginUser.username)){usernameMsg.value="格式有误"return false}usernameMsg.value="OK"return true}function checkUserPwd(){let userPwdReg = /^[0-9]{6}$/if(!userPwdReg.test(loginUser.userPwd)){userPwdMsg.value="格式有误"return false}userPwdMsg.value="OK"return true}async function login(){// 表单数据格式都正确再提交let flag1 =checkUsername()let flag2 =checkUserPwd()if(!(flag1 && flag2)){return }let {data} = await request.post("user/login",loginUser) //发送请求if(data.code == 200 ){alert("登录成功")console.log(data)// 获得登录的用户信息,更新到pinia中sysUser.uid =data.data.loginUser.uid    //pinia获取登入信息sysUser.username = data.data.loginUser.username// 跳转到showSchedulerouter.push("/showSchedule")} else if( data.code == 503){alert("密码有误")}else if (data.code == 501 ){alert("用户名有误")}else {alert("未知错误")}}</script><template><div><h3 class="ht">请登录</h3><table class="tab" cellspacing="0px"><tr class="ltr"><td>请输入账号</td><td><input class="ipt" type="text" v-model="loginUser.username"@blur="checkUsername()"><span id="usernameMsg" v-text="usernameMsg"></span></td></tr><tr class="ltr"><td>请输入密码</td><td><input class="ipt" type="password" v-model="loginUser.userPwd"@blur="checkUserPwd()"><span id="userPwdMsg" v-text="userPwdMsg"></span></td></tr><tr class="ltr"><td colspan="2" class="buttonContainer"><input class="btn1" type="button" @click="login()" value="登录"><input class="btn1" type="button" value="重置"><router-link to="/regist"><button class="btn1">去注册</button></router-link></td></tr></table></div>
</template><style scoped>.ht{text-align: center;color: cadetblue;font-family: 幼圆;}.tab{width: 500px;border: 5px solid cadetblue;margin: 0px auto;border-radius: 5px;font-family: 幼圆;}.ltr td{border: 1px solid  powderblue;}.ipt{border: 0px;width: 50%;}.btn1{border: 2px solid powderblue;border-radius: 4px;width:60px;background-color: antiquewhite;}#usernameMsg , #userPwdMsg {color: gold;}.buttonContainer{text-align: center;}
</style>

3.3定义注册组件 Regist.vue

<script setup>import {ref,reactive} from 'vue'/* 导入发送请求的axios对象 */import request from'../utils/request'import {useRouter} from 'vue-router'const router = useRouter()let registUser = reactive({username:"",userPwd:""})let usernameMsg=ref('')let userPwdMsg=ref('')let reUserPwdMsg=ref('')let reUserPwd=ref('')async function checkUsername(){let usernameReg= /^[a-zA-Z0-9]{5,10}$/if(!usernameReg.test(registUser.username)){usernameMsg.value="格式有误"return false}// 发送异步请求   继续校验用户名是否被占用let {data} = await request.post(`user/checkUsernameUsed?username=${registUser.username}`)if(data.code != 200){usernameMsg.value="用户名占用"return false}usernameMsg.value="可用"return true}function checkUserPwd(){let userPwdReg = /^[0-9]{6}$/if(!userPwdReg.test(registUser.userPwd)){userPwdMsg.value="格式有误"return false}userPwdMsg.value="OK"return true}function checkReUserPwd(){let userPwdReg = /^[0-9]{6}$/if(!userPwdReg.test(reUserPwd.value)){reUserPwdMsg.value="格式有误"return false}if(registUser.userPwd != reUserPwd.value){reUserPwdMsg.value="两次密码不一致"return false}reUserPwdMsg.value="OK"return true}// 注册的方法async function regist(){// 校验所有的输入框是否合法let flag1 =await checkUsername()let flag2 =await checkUserPwd()let flag3 =await checkReUserPwd()if(flag1 && flag2 && flag3){let  {data}= await request.post("user/regist",registUser)//  let  {data}=  request.post("user/regist",registUser)if(data.code == 200){// 注册成功跳转 登录页alert("注册成功,快去登录吧")router.push("/login")}else{alert("抱歉,用户名被抢注了")}}else{alert("校验不通过,请求再次检查数据")}}function clearForm(){registUser.username=""registUser.userPwd=""usernameMsg.value=""userPwdMsg.value=""reUserPwd.value=""reUserPwdMsg.value=""}</script><template><div><h3 class="ht">请注册</h3><table class="tab" cellspacing="0px"><tr class="ltr"><td>请输入账号</td><td><input class="ipt" id="usernameInput" type="text" name="username" v-model="registUser.username"@blur="checkUsername()"><span id="usernameMsg" class="msg" v-text="usernameMsg"></span></td></tr><tr class="ltr"><td>请输入密码</td><td><input class="ipt" id="userPwdInput" type="password" name="userPwd" v-model="registUser.userPwd"@blur="checkUserPwd()"><span id="userPwdMsg" class="msg" v-text="userPwdMsg"></span></td></tr><tr class="ltr"><td>确认密码</td><td><input class="ipt" id="reUserPwdInput" type="password" v-model="reUserPwd"@blur="checkReUserPwd()"><span id="reUserPwdMsg" class="msg" v-text="reUserPwdMsg"></span></td></tr><tr class="ltr"><td colspan="2" class="buttonContainer"><input class="btn1" type="button" @click="regist()" value="注册"><input class="btn1" type="button" @click="clearForm()" value="重置"><router-link to="/login"><button class="btn1">去登录</button></router-link></td></tr></table></div>
</template>
<style scoped>.ht{text-align: center;color: cadetblue;font-family: 幼圆;}.tab{width: 500px;border: 5px solid cadetblue;margin: 0px auto;border-radius: 5px;font-family: 幼圆;}.ltr td{border: 1px solid  powderblue;}.ipt{border: 0px;width: 50%;}.btn1{border: 2px solid powderblue;border-radius: 4px;width:60px;background-color: antiquewhite;}.msg {color: gold;}.buttonContainer{text-align: center;}
</style>

3.4定义主体显示内容组件ShowSchedule.vue

<script setup>/* 导入pinia数据 */import {defineUser} from '../store/userStore.js'import {defindSchedule} from '../store/scheduleStore.js'let sysUser = defineUser()let schedule = defindSchedule()import {ref,reactive,onUpdated,onMounted} from 'vue'import request from '../utils/request'//挂载完毕后,立刻查询当前用户的所有日程信息,赋值给piniaonMounted(async ()=>{showSchedule()})// 查询当前用户所有日程信息 并展示到视图的方法async function showSchedule(){// 发送异步请求,获得当前用户的所有日程记录let {data} = await request.get("schedule/findAllSchedule",{params:{"uid":sysUser.uid}})schedule.itemList = data.data.itemList}// 为当前用户增加一个空的日程记录async function addItem(){let{data} = await request.get('schedule/addDefaultSchedule',{params:{"uid":sysUser.uid}})  if(data.code == 200){// 增加成功,刷新页面数据showSchedule()}else{alert("增加失败")}}async function updateItem(index){// 找到要修改的数据 发送给服务端,更新进入数据库即可let {data} =  await request.post("schedule/updateSchedule",schedule.itemList[index])   if(data.code == 200){showSchedule()alert("更新成功")}else{alert("更新失败")}}async function removeItem(index){let sid =schedule.itemList[index].sidlet {data} = await request.get(`schedule/removeSchedule`,{params:{"sid":sid}})if(data.code == 200){showSchedule()alert("删除成功")}else{alert("删除失败")}}</script><template><div><h3 class="ht">您的日程如下</h3>
<table class="tab" cellspacing="0px"><tr class="ltr"><th>编号</th><th>内容</th><th>进度</th><th>操作</th></tr><tr class="ltr" v-for="item,index in schedule.itemList" :key="index"><td v-text = "index+1"></td><td ><input type="text" v-model="item.title"></td><td ><input type="radio"  value="1" v-model="item.completed"> 已完成<input type="radio"  value="0" v-model="item.completed"> 未完成</td><td class="buttonContainer"><button class="btn1" @click="removeItem(index)">删除</button><button class="btn1" @click="updateItem(index)">保存修改</button></td></tr><tr class="ltr buttonContainer" ><td colspan="4"><button class="btn1" @click="addItem()">新增日程</button></td></tr>
</table></div>
</template><style scoped>.ht{text-align: center;color: cadetblue;font-family: 幼圆;}.tab{width: 80%;border: 5px solid cadetblue;margin: 0px auto;border-radius: 5px;font-family: 幼圆;}.ltr td{border: 1px solid  powderblue;}.ipt{border: 0px;width: 50%;}.btn1{border: 2px solid powderblue;border-radius: 4px;width:100px;background-color: antiquewhite;}#usernameMsg , #userPwdMsg {color: gold;}.buttonContainer{text-align: center;}</style>

3.5放入主组件 APP.vue

<script setup>import Header from './components/Header.vue'
</script><template><div><Header></Header><hr><router-view></router-view></div></template><style scoped>
</style>

项目实战一结束

项目实战二

项目结构

1.创建项目,导入所需依赖

这里照着dependencies里面的依赖下载就行

{"name": "my-vue3-vite-project","private": true,"version": "0.0.0","type": "module","scripts": {"dev": "vite","build": "vite build","preview": "vite preview"},"dependencies": {"axios": "^1.4.0","element-plus": "^2.2.5","less": "^4.1.3","less-loader": "^7.3.0","mitt": "^3.0.0","nprogress": "^0.2.0","pinia": "^2.0.14","vue": "^3.2.47","vue-router": "^4.1.6"},"devDependencies": {"@vitejs/plugin-vue": "^4.1.0","typescript": "^4.7.2","vite": "^4.3.2"}
}

2.定义依赖对象相关文件(.js)

2.1路由

index.js

import { createRouter, createWebHistory } from "vue-router";
import { staticRoutes } from "./routes";
import { useUserInfoStore } from '../stores/userInfo';
import pinia from '../stores';
import { getToken, removeToken } from '../utils/token-utils';
import { ElMessage } from 'element-plus';const router = createRouter({history: createWebHistory(),routes: staticRoutes,
});const userInfoStore = useUserInfoStore(pinia)//全局前置守卫
router.beforeEach(async (to, from, next) => {const token = getToken()const userInfo = !!userInfoStore.nickNameif (token) {if (to.path == "/login") {next({ path: "/" })} else {if (userInfo) {next()} else {try {await userInfoStore.getInfo()next()} catch (error) {removeToken()}}}} else {next()}
});// //使用全局后置钩子配置关闭进度条
// router.afterEach(() => {
//   NProgress.done();
// });// 导出路由
export default router;

router.js


export const staticRoutes = [{path: "/",redirect: "/headlinenews",},{// 头条path: "/headlinenews",component: () => import("../pages/HeadlineNews/index.vue"),name: "HeadlineNews",},{//头条详情path: "/detail",component: () => import("../pages/Detail/index.vue"),name: "Detail",},{// 登录path: "/login",component: () => import("../pages/Login/index.vue"),name: "Login",},{//注册path: "/register",component: () => import("../pages/Register/index.vue"),name: "Register",},{//发布新闻的页面path: "/addormodifynews",component: () => import("../pages/addOrModifyNews/index.vue"),name: "addOrModifyNews",},
];

2.2axios

import axios from "axios";
import { ElMessage } from 'element-plus';
import pinia from '../stores/index';
import { useUserInfoStore } from '../stores/userInfo';
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// 配置新建一个 axios 实例
const service = axios.create({baseURL: "/app-dev/",timeout: 50000,
});// 添加请求拦截器
service.interceptors.request.use((config) => {NProgress.start()//开启进度条// 如果有token, 通过请求头携带给后台const userInfoStore = useUserInfoStore(pinia) // 如果不是在组件中调用,必须传入piniaconst token = userInfoStore.tokenif (token) {// config.headers['token'] = token  // 报错: headers对象并没有声明有token, 不能随便添加(config.headers)['token'] = token}return config;
});// 添加响应拦截器
service.interceptors.response.use((response) => {NProgress.done()//关闭进度条if(response.data.code !== 200){// 判断响应状态码if (response.data.code == 501)  return  Promise.reject(ElMessage.error("用户名有误"))else if (response.data.code == 503) return  Promise.reject(ElMessage.error("密码有误"))else if (response.data.code == 504) return  Promise.reject(ElMessage.error("登录已过期"))else if (response.data.code == 505) return  Promise.reject(ElMessage.error("用户名占用"))} else {return response.data.data; /* 返回成功响应数据中的data属性数据 */}},(error) => {NProgress.done()//关闭进度条return Promise.reject(error.message);}
);export default service;

2.3token

const TokenKey = 'vue_admin_template_token'export function getToken() {return localStorage.getItem(TokenKey)
}export function setToken(token: string) {localStorage.setItem(TokenKey, token)
}export function removeToken() {localStorage.removeItem(TokenKey)
}

2.4pinia

import { createPinia } from 'pinia';const pinia = createPinia();export default pinia;
2.4.1pinia存储

import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import { getLogin,getUserInfo } from '../api/index';/*** 用户信息* @methods setUserInfos 设置用户信息*/
export const useUserInfoStore = defineStore('userInfo', {state: () => ({token: getToken(),nickName: '',uid: '',}),actions: {// 登陆的异步actionasync login (loginForm) {// 发送登陆的请求const result = await getLogin(loginForm)// 请求成功后, 取出token保存  pinia和local中const token = result.tokenthis.token = tokensetToken(token)},async getInfo () {const result = await getUserInfo()this.nickName = result.loginUser.nickNamethis.uid = result.loginUser.uid},initUserInfo(){removeToken()this.nickName = ""this.uid = ""console.log('1111111111');}},});

2.5api

import request from "../utils/request/"// portal/findAllTypes
//获取分类列表
export const getfindAllTypes = () => {return request.get("portal/findAllTypes");
};
// 分页带条件查询所有头条
export const getfindNewsPageInfo = (info) => {return request.post("portal/findNewsPage",info);
};
// 查看头条详情
export const getshowHeadlineDetail = (id) => {return request({method: "post",url: "portal/showHeadlineDetail",headers: {"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",},data:`hid=${id}`});
};//删除的回调
// headline/removeByHid
export const removeByHid = (id) => {return request({method: "post",url: "headline/removeByHid",headers: {"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",},data:`hid=${id}`})
};//登录的接口
export const getLogin = (info) => {return request.post("user/login",info);
};
//获取用户信息的接口
export const getUserInfo = (info) => {return request.get("user/getUserInfo");
};//注册校验的接口  user/checkUserName
export const registerValidateApi = (username) => {return request({method: "post",url: "user/checkUserName",headers: {"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",},data:`username=${username}`})
};// 注册的接口
export const registerApi = (userInfo) => {return request.post("user/regist",userInfo)
}
//判断用户登录过期的接口
export const isUserOverdue = () => {return request.get("user/checkLogin")
}// 修改头条回显的接口
export const getFindHeadlineByHid = (id) => {return request({method: "post",url: "headline/findHeadlineByHid",headers: {"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",},data:`hid=${id}`});
};//点击保存修改的回调
// headline/update
export const saveOrAddNews = (news) => {return request.post("headline/update",news)
}// headline/publish
export const issueNews = (news) => {return request.post("headline/publish",news)
}

3组件

3.1头组件Header.vue

<template><div class="headerContainer"><!-- 头部左侧区域 --><div class="left"><ul><li @click="HighlightHandler(index,)"  v-for="(item,index) in findAllTypeList" :key="item.tid"><a :class="{ active: item.isHighlight }" href="javascript:;">{{item.tname}}</a></li></ul></div><!-- 头部右侧区域 --><div class="right"><div class="rightInput" style="margin-right: 50px;"><el-input v-model="keywords" placeholder="搜索最新头条"></el-input><!-- <el-button   type="primary">搜索</el-button> --></div><!-- 用户登录以后的展示 --><div class="btn-dropdown"><!-- 用户没有登录的时候的展示 --><div v-if="nickName" style="display: flex; justify-content: center; align-items: center;"><el-dropdown><el-button type="primary">您好:{{ nickName }}<el-icon class="el-icon--right"><arrow-down /></el-icon></el-button><template #dropdown><el-dropdown-menu><el-dropdown-item @click="handlerNews">发布新闻</el-dropdown-item><el-dropdown-item>个人中心</el-dropdown-item><el-dropdown-item>浏览记录</el-dropdown-item><el-dropdown-item @click="Logout">退出登录</el-dropdown-item></el-dropdown-menu></template></el-dropdown></div><div v-else class="containerButton"><el-button size="small" style="background: #212529; color: #aea7a2" @click="toLogin">登录</el-button><el-button size="small" style="background: #ffc107; color: #684802" @click="toRegister">注册</el-button></div></div></div></div>
</template><script>
import { defineComponent } from 'vue'
export default defineComponent({name: 'Header'
})
</script><script setup>
import { getfindAllTypes, isUserOverdue } from '../api/index'
import { ref, onMounted , getCurrentInstance ,watch, onUpdated} from "vue"
import { useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import { removeToken } from '../utils/token-utils' 
import pinia from '../stores/index';
import { useUserInfoStore } from '../stores/userInfo'
const userInfoStore = useUserInfoStore(pinia)
const nickName = ref("")
// 获取到 全局事件总线
const { Bus } = getCurrentInstance().appContext.config.globalProperties
const router = useRouter()
const keywords = ref("") // 收集搜索最新头条参数
//监视搜索参数的变化 ,当搜索参数变化的时候给HeadlineNews组件传递数据
watch(keywords, (newVal) => {Bus.emit('keyword', newVal)
})
const findAllTypeList = ref([])//所有头条分类
const toLogin = () => {
router.push({ name: "Login" });
}
//点击去注册页面
const toRegister = () => {router.push({ name: "Register" });
}
const getList = async () => {let result = await getfindAllTypes()// 遍历数据添加高亮标识result.forEach((item) => {item.tid = item.tiditem.tname = item.tnameitem.isHighlight = false})// 添加微头条数据result.unshift({isHighlight: true,tid: 0,tname: "微头条"})findAllTypeList.value = result
}
// 页面挂载的生命周期回调
onUpdated(() => {nickName.value = userInfoStore.nickName
})
onMounted(() => {getList()
})//点击切换高亮的回调(排他思想)
const HighlightHandler = (index) => {findAllTypeList.value.forEach((item) => {item.isHighlight = false})// 切换高亮的时候把tid传给HeadlineNews组件findAllTypeList.value[index].isHighlight = trueBus.emit('tid', findAllTypeList.value[index].tid)
}// 点击退出登录的回调
const Logout = () => {removeToken()userInfoStore.initUserInfo()nickName.value = ""router.go({ name: "HeadlineNews" });
}//点击发布新闻的回调
const handlerNews = async () => {//发送请求判断用户是否token过期await isUserOverdue()router.push({ name: "addOrModifyNews" });
}
</script><style>
.el-dropdown {vertical-align: top;width: 100px;
}.el-dropdown+.el-dropdown {margin-left: 15px;
}.el-icon-arrow-down {font-size: 12px;
}
</style><style lang="less" scoped>
.headerContainer {width: 100%;height: 60px;background: #212529;display: flex;justify-content: space-around;.left {ul {display: flex;li {list-style: none;margin-left: 20px;a:-webkit-any-link {text-decoration: none;color: #59646b;&.active {color: #c0adab;}}}}}.right {.containerButton {display: flex;align-items: center;}line-height: 60px;display: flex;flex-wrap: nowrap;.rightInput {display: flex;align-items: center;:deep(.el-input__inner) {height: 30px;width: 150px;}}.btn-dropdown{display: flex;align-items: center;}:deep(.el-button) {margin: 0 0 0 10px;display: flex;justify-content: center;align-items: center;}}
}.example-showcase .el-dropdown + .el-dropdown {margin-left: 15px;
}
.example-showcase .el-dropdown-link {cursor: pointer;color: var(--el-color-primary);display: flex;align-items: center;
}
</style>

3.2安装上面顺序第一个

<template><el-card class="box-card AddNewsContainer"><el-form :rules="newsRules" :model="formData" ref="formRef" size="default"><el-form-item label="文章标题" prop="title"><el-input v-model="formData.title" placeholder="请输入标题"></el-input></el-form-item><el-form-item style="margin: 50px 0;" label="文章内容" prop="article"><el-input v-model="formData.article" type="textarea" rows="8"></el-input></el-form-item><el-form-item label="文章内容"  prop="type"><el-select v-model="formData.type" placeholder="请选择文章类别"><el-option v-for="item in article" :label="item.name" :value="item.type"></el-option></el-select></el-form-item></el-form><el-form-item><el-button   @click="handlerCancel">取消</el-button><el-button type="primary"  @click="handlerSave">保存</el-button></el-form-item></el-card>
</template><script>
import { defineComponent } from 'vue'
import { isUserOverdue } from '../../api/index'
export default defineComponent({name: 'AddNews'
})
</script>
<script  setup>
import { getFindHeadlineByHid , saveOrAddNews, issueNews } from "../../api/index"
import { ref, onMounted } from "vue"
import { useRoute } from 'vue-router'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
const router = useRouter() 
const route = useRoute() const formRef = ref()
// 校验规则
const validateType = (rule, value, callback) => {if (value.length) {callback()} else {callback(new Error('文章标题是必须的'))}
}
// 校验规则
const validateArticle = (rule, value, callback) => {if (value.length) {callback()} else {callback(new Error('文章内容是必须的'))}
}
// 校验规则
const validateTitle = (rule, value, callback) => {if (value.length) {callback()} else {callback(new Error('文章类别是必须的'))
}
}
// 校验规则
const newsRules = {title: [{ required: true, trigger: 'blur', validator: validateTitle }],article: [{ required: true, trigger: 'blur', validator: validateArticle }],type: [{ required: true, validator: validateType }],
}const formData = ref({hid:null,title: "",   // 文章标题article: "", // 文章内容type: ""     // 文章类别
})
//初始化文章类别数据
const article = [{type: "1",name: "新闻"},{type: "2",name: "体育"},{type: "3",name: "娱乐"},{type: "4",name: "科技"},{type: "5",name: "其他"}
]
// 如果是点击修改的话 路由就会携带hid参数  就要发送请求 获取数据回显
const clickModifyEcho = async () => {if (!route.query.hid)  returnlet result = await getFindHeadlineByHid(route.query.hid)formData.value.title = result.headline.titleformData.value.article = result.headline.articleformData.value.type = result.headline.type === 1 ? "新闻" : result.headline.type === 2 ? "体育" : result.headline.type === 3 ? "娱乐" : result.headline.type === 4 ? "科技" : "其他" 
}
//页面挂载生命周期
onMounted(() => {clickModifyEcho()
})
//点击取消的回调
const handlerCancel = () => {router.back()
}
//点击保存的回调
const handlerSave = async () => {await formRef.value?.validate()//发送请求判断用户是否token过期await isUserOverdue()
const Obj = {...formData.value}//整理请求参数
//  Obj.hid = userInfoStore.uid.toString()  //添加用户id 让后端知道谁添加的Obj.hid = route.query.hid  //添加用户id 让后端知道谁添加的
// 判断type类型if(Obj.type == "新闻" ) Obj.type = "1"if(Obj.type == "体育" ) Obj.type = "2"if(Obj.type == "娱乐" ) Obj.type = "3"if(Obj.type == "科技" ) Obj.type = "4"if (Obj.type == "其他") Obj.type = "5"//发送请求if (route.query.hid) {await saveOrAddNews(Obj)ElMessage.success("修改成功")}else {await issueNews(formData.value)ElMessage.success("添加成功")}router.push({ name: "HeadlineNews" });
}</script><style lang="less" scoped>
.AddNewsContainer {width: 600px;margin: 150px auto;
}
</style>

3.3第二个

<template><div class="seeDetails"><div><h4>{{ detailList.title }}</h4></div><div style="margin-right: 250px"><span>{{ detailList.typeName }}</span><span>{{ detailList.pageViews }}浏览</span><span>{{ detailList.pastHours }}小时前</span></div><div style="width: 500px; margin: 20px 0px 0px 70px"><p>{{ detailList.article }}</p></div></div>
</template><script >import { defineComponent } from 'vue'export default  defineComponent({name:'Detail'})
</script>
<script  setup>
import { getshowHeadlineDetail } from "../../api/index"
import { ref , onMounted } from "vue"
import { useRoute } from 'vue-router'
const route = useRoute() // 路由信息对象const detailList = ref({}) //详情数据
//获取详情初始化数据
const getDetailList = async () => {let result = await getshowHeadlineDetail(route.query.hid)detailList.value = result.headline
}
// 页面初始化钩子
onMounted(() => {getDetailList()
})</script><style lang="less" scoped>
.seeDetails {width: 1200px;margin: 0 auto;display: flex;flex-direction: column;align-items: center;div {span {padding-right: 15px;font-size: 14px;color: #8d91aa;}p {font-size: 14px;color: #2b2e30;}}
}
</style>

3.4第三个

<template><div class="container"><div class="listItem"><!-- 每一项头条列表 --><div class="containerItem" v-for="item in pageData" :key="item.hid"><div><span class="text">{{ item.title }}</span></div><div class="detail"><span>{{ item.type == 1 ? "新闻":item.type == 2 ? "体育": item.type == 3 ? "娱乐": item.type == 4 ? "科技" : "其他" }}</span><span>{{item.pageViews}}浏览</span><span>{{item.pastHours}}小时前</span></div><div><el-button @click="toDetail(item.hid)" size="small"style="background: #198754; margin-left: 15px; color: #bbd3dc">查看全文</el-button><el-popconfirm v-if="item.publisher == type" @confirm="handlerDelete(item.hid)" :title="`您确定要删除${item.title}吗?`"><template #reference><el-button    size="small" style="background: #dc3545; color: #bbd3dc">删除</el-button></template></el-popconfirm><el-button @click="Modify(item.hid)" v-if="item.publisher == type"  size="small" style="background: #212529; color: #bbd3dc">修改</el-button></div></div><!-- 分页器 --><div style="margin-top: 20px"><el-pagination v-model:current-page="findNewsPageInfo.pageNum"v-model:page-size="findNewsPageInfo.pageSize" @size-change="getPageList"@current-change="getPageList":page-sizes="[5,7,10]" backgroundlayout="prev, pager, next , ->, sizes, total" :total="totalSize" /></div></div></div>
</template><script >
import { getfindNewsPageInfo , removeByHid } from "../../api/index"import { defineComponent } from 'vue'export default  defineComponent({name:'HeadlineNews'})
</script>
<script  setup>
import { ref, onMounted, getCurrentInstance, watch } from "vue"
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import pinia from '../../stores/index';
import { useUserInfoStore } from '../../stores/userInfo'
const  { Bus } = getCurrentInstance().appContext.config.globalProperties
const userInfoStore = useUserInfoStore(pinia)
const router = useRouter()
const type = userInfoStore.uid
const findNewsPageInfo = ref({keyWords: "", // 搜索标题关键字type: 0,           // 新闻类型pageNum: 1,        // 页码数pageSize: 5,     // 页大小}
)
const totalSize = ref(0) //分页总数量
// 初始化列表数据
const pageData = ref([{hid: null,pageViews: null,pastHours: null,publisher: null,title: "",type: null
}])//接收header组件用户搜索的数据
Bus.on('keyword', (keywords) => {findNewsPageInfo.value.keyWords = keywords
})
// header点击切换高亮的时候传递过来的tid
Bus.on('tid', (type) => {findNewsPageInfo.value.type = type
})
// 监视初始化参数type的变化,当type发生改变的时候重新发送请求获取列表数据
watch(() => findNewsPageInfo.value, () => {getPageList()
}, {deep: true,
})
// 初始化请求分页列表数据
const getPageList = async () => {let result = await getfindNewsPageInfo(findNewsPageInfo.value)pageData.value = result.pageInfo.pageDatafindNewsPageInfo.value.pageNum = result.pageInfo.pageNumfindNewsPageInfo.value.pageSize = result.pageInfo.pageSizetotalSize.value = +result.pageInfo.totalSize
}
// 组件挂载的生命周期钩子
onMounted(() => {getPageList()
})
// 点击查看全文的回调
const toDetail = (hid) => {router.push({ name: "Detail" ,query:{ hid }});
}// 点击删除的回调
const handlerDelete = async (id) => {await removeByHid(id)ElMessage.success('删除成功!')//重新获取列表请求getPageList()
}
//点击修改的回调
const Modify = (hid) => {router.push({ name: "addOrModifyNews", query: { hid } });
}
</script><style lang="less" scoped>
.container {width: 1200px;margin: 0 auto;display: flex;flex-direction: column;align-items: center;// 列表样式.listItem {.containerItem {margin-top: 20px;border-radius: 10px;border: 2px solid #ebebeb;width: 600px;height: 120px;div {margin-top: 10px;}.text {margin-left: 15px;color: #353a3f;}.detail {span {margin-left: 15px;color: #8b778a;font-size: 14px;}}}}
}
</style>

3.5第四个

<template><div class="login-container"><el-form:model="loginForm"ref="formRef"label-width="80px"class="login-form":rules="loginRules" ><h2>用户登录</h2><el-form-item label="用户名" prop="username"><el-inputv-model="loginForm.username"ref="username"name="username"autocomplete="off"placeholder="请输入用户名"></el-input></el-form-item><el-form-item label="密码" prop="userPwd"><el-inputtype="password"v-model="loginForm.userPwd"autocomplete="off"placeholder="请输入密码"></el-input></el-form-item><el-form-item><el-button type="success" @click.native.prevent="login">登录</el-button><el-button type="primary" @click="toRegister">注册</el-button></el-form-item></el-form></div>
</template><script lang="ts">import { defineComponent } from 'vue'export default  defineComponent({name:'Login'})
</script>
<script lang="ts" setup>
import { ref } from "vue"
import { useUserInfoStore } from '../../stores/userInfo';import type { FormInstance } from 'element-plus';
import { useRouter } from 'vue-router'
const userInfoStore = useUserInfoStore()
const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
//账号密码参数
const loginForm = ref({username: "zhangsan",userPwd: "123456",
})
// 校验规则
const validateUsername = (rule: any, value: any, callback: any) => {if (value.length < 4) {callback(new Error('用户名长度不能小于4位'))} else {callback()}
}
// 校验规则
const validatePassword = (rule: any, value: any, callback: any) => {if (value.length < 6) {callback(new Error('密码长度不能小于6位'))} else {callback()}
}
// 校验规则
const loginRules = {username: [{ required: true, validator: validateUsername }],userPwd: [{ required: true, trigger: 'blur', validator: validatePassword }]
}
//点击登录的回调
const login = async () => {// console.log('点击登录');await formRef.value?.validate()loading.value = truetry {// await getUserInfo(loginForm.value)await userInfoStore.login(loginForm.value)router.push({ name: "HeadlineNews" });} finally {loading.value = false}// loading.value = true// const { username, userPwd } = loginForm.value// try {//   await userInfoStore.login(username, userPwd)//   router.push({ path: redirect.value || '/' })// } finally {//   loading.value = false// }
}const toRegister = ()=> {router.push({ name: "Register" });
}
</script><style scoped>
.login-container {display: flex;justify-content: center;align-items: center;height: 100vh;
}
.login-form {width: 400px;text-align: center;
}
</style>

3.6第五个

<template><div class="register-container"><el-form:model="registerForm"ref="formRef"label-width="80px"class="register-form":rules="registerRules"><h2>用户注册</h2><el-form-item label="姓名" prop="nickName"><el-inputv-model="registerForm.nickName"autocomplete="off"ref="nickName"name="nickName"placeholder="请输入姓名"></el-input></el-form-item><el-form-item label="用户名" prop="username"><el-inputv-model="registerForm.username"autocomplete="off"ref="username"name="username"placeholder="请输入用户名"></el-input></el-form-item><el-form-item label="密码" prop="userPwd"><el-inputtype="password"v-model="registerForm.userPwd"ref="userPwd"name="userPwd"autocomplete="off"placeholder="请输入密码"></el-input></el-form-item><!-- prop="confirmPassword" --><el-form-item label="确认密码"  prop="confirmPassword"><el-inputtype="password"v-model="registerForm.confirmPassword"autocomplete="off"ref="confirmPassword"name="confirmPassword"placeholder="请确认密码"></el-input></el-form-item><el-form-item><el-button type="primary" @click="register">注册</el-button><el-button type="danger" @click="resetForm">重置</el-button><el-button type="success" @click="goLogin">去登录</el-button></el-form-item></el-form></div>
</template><script lang="ts">import { defineComponent } from 'vue'export default  defineComponent({name:'Register'})
</script>
<script lang="ts" setup>
import { ref } from "vue"
import { useRouter } from 'vue-router'
import { ElMessage, FormInstance } from 'element-plus';
import { registerValidateApi, registerApi } from "../../api/index"
const router = useRouter()
// 初始化注册参数
const registerForm = ref({username: "",userPwd: "",confirmPassword: "",nickName:''
})
const formRef = ref<FormInstance>()// 校验规则
const validateUsername = (rule: any, value: any, callback: any) => {if (value.length < 4) {callback(new Error('用户名长度不能小于4位'))} else {callback()}
}
// 校验规则
const validatePassword = (rule: any, value: any, callback: any) => {if (value.length < 6) {callback(new Error('密码长度不能小于6位'))} else {callback()}
}
// 校验规则
const validateConfirmPassword = (rule: any, value: any, callback: any) => {if (value.length < 6) {callback(new Error('密码长度不能小于6位'))} else {callback()}
}
// 校验规则
const validateNickName = (rule: any, value: any, callback: any) => {if (value.length >= 2  && value.length  <= 6  ) {callback()} else {callback(new Error('姓名必须在2-6位'))
}
}
// 校验规则
const registerRules = {nickName: [{ required: true, trigger: 'blur', validator: validateNickName }],username: [{ required: true, validator: validateUsername }],userPwd: [{ required: true, trigger: 'blur', validator: validatePassword }],confirmPassword: [{ required: true, trigger: 'blur', validator: validateConfirmPassword }]
}//点击注册的回调
const register = async () => {await formRef.value?.validate()if (registerForm.value.userPwd == registerForm.value.confirmPassword) {// 调用用户名校验接口await registerValidateApi(registerForm.value.username)//  整理参数const obj = {username: "",userPwd: "",nickName: ''}obj.username = registerForm.value.usernameobj.userPwd = registerForm.value.userPwdobj.nickName = registerForm.value.nickName//  调用注册接口await registerApi(obj)formRef.value?.resetFields()ElMessage.success("注册成功")} else {return ElMessage.error("密码和确定密码必须一致")}}
//点击去登录的回调
const goLogin = () => {router.push({path:"/login"})
}//点击重置的回调
const resetForm = () => {//重置表单formRef.value?.resetFields()
}</script><style scoped>
.register-container {display: flex;justify-content: center;align-items: center;height: 100vh;
}
.register-form {width: 400px;text-align: center;
}
</style>

3.7一起加入主题组件App.vue

<template><div ><Header v-show="isHeader"></Header><router-view></router-view></div>
</template><script >
import Header from './components/Header.vue'import { defineComponent } from 'vue'export default  defineComponent({name:'App'})
</script>
<script  setup>
import { computed } from "vue"
import { useRoute } from 'vue-router'
const route = useRoute() // 路由信息对象
// 判断是否显示header组件const isHeader =  computed(() => {return route.name !== "Login" && route.name !== "Register" && route.name !== "addNews";
})</script><style lang="less" scoped></style>

项目实战二结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/385505.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HarmonyOS Next 省市区级联(三级联动)筛选框

效果图 完整代码 实例对象 export class ProvinceBean {id?: stringpid?: stringisSelect?: booleandeep?: objectextName?: stringchildren?: ProvinceBean[] }级联代码 import { MMKV } from tencent/mmkv/src/main/ets/utils/MMKV import { ProvinceBean } from ..…

nodeselector

1.概述 在创建pod资源是&#xff0c;k8s集群系统会给我们将pod资源随机分配到不同服务器上。我们通过配置nodeSelector可以将pod资源指定到拥有某个标签的服务器上 使用nodeselector前我们要先给每个节点打上标签&#xff0c;在编辑pod资源的时候选择该标签 2.示例 给节点打标…

数据科学统计面试问题 -40问

前 40 名数据科学统计面试问题 一、介绍 正如 Josh Wills 曾经说过的那样&#xff0c;“数据科学家是一个比任何程序员都更擅长统计、比任何统计学家都更擅长编程的人”。统计学是数据科学中处理数据及其分析的基本工具。它提供了工具和方法&#xff0c;可帮助数据科学家获得…

初涉JVM

JVM 字节码、类的生命周期、内存区域、垃圾回收 JVM主要功能&#xff1a; 解释运行&#xff08;翻译字节码&#xff09;内存管理&#xff08;GC&#xff09;即使编译&#xff08;Just - In - Time&#xff0c; JIT&#xff09; 将短时间内常使用到的字节码翻译成机器码存储在内…

【Gin】智慧架构的巧妙砌筑:Gin框架中控制反转与依赖注入模式的精华解析与应用实战(下)

【Gin】智慧架构的巧妙砌筑&#xff1a;Gin框架中控制反转与依赖注入模式的精华解析与应用实战(下) 大家好 我是寸铁&#x1f44a; 【Gin】智慧架构的巧妙砌筑&#xff1a;Gin框架中控制反转与依赖注入模式的精华解析与应用实战(下)✨ 喜欢的小伙伴可以点点关注 &#x1f49d; …

uboot的mmc partconf命令

文章目录 命令格式参数解释具体命令解释总结 mmc partconf 是一个用于配置 MMC (MultiMediaCard) 分区的 U-Boot 命令。具体来说&#xff0c;这个命令允许你设置或读取 MMC 卡的分区配置参数。让我们详细解释一下 mmc partconf 0 0 1 0 命令的含义。 命令格式 mmc partconf &…

【网络安全】子域名模糊测试实现RCE

未经许可&#xff0c;不得转载。 文章目录 正文总结 正文 在之前测试一个私人项目时&#xff0c;我报告了admin.Target.com上的Auth Bypass漏洞&#xff0c;这将导致SQLI&RCE &#xff0c;该漏洞在报告后仅一天就被修复。 现在重拾该应用程序&#xff0c;对子域进行模糊测…

探索 Blockly:自定义积木实例

3.实例 3.1.基础块 无输入 , 无输出 3.1.1.json var textOneJson {"type": "sql_test_text_one","message0": " one ","colour": 30,"tooltip": 无输入 , 无输出 };javascriptGenerator.forBlock[sql_test_te…

c语言第四天笔记

关于 混合操作&#xff0c;不同计算结果推理 第一种编译结果&#xff1a; int i 5; int sum (i) (i) 6 7 13 第二种编译结果&#xff1a; int i 5; int sum (i) (i) 6 7 7 7 前面的7是因为后面i的变化被影响后&#xff0c;重新赋值 14 第一种编译结果&#xff…

后端解决跨域(Cross-Origin Resource Sharing)(三种方式)

注解CrossOrigin 控制层的类上或者方法上加注解CrossOrigin 实现接口并重写方法 Configuration public class CorsConfig implements WebMvcConfigurer {Overridepublic void addCorsMappings(CorsRegistry registry) {// 设置允许跨域的路径registry.addMapping("/**&qu…

springboot配置文件如何读取pom.xml的值

比如想读取profile.active的值&#xff0c;默认属性为pro 在maven中加入以下插件&#xff1a; <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>3.2.0</version>&l…

Servlet详解(超详细)

Servlet详解 文章目录 Servlet详解一、基本概念二、Servlet的使用1、创建Servlet类2、配置Servleta. 使用web.xml配置b. 使用注解配置 3、部署Web应用4、处理HTTP请求和生成响应5、处理表单数据HTML表单Servlet 6、管理会话 三、servlet生命周期1、加载和实例化2、初始化3、 请…

pinia安装及简介

pinia简介 基本特点 轻量级&#xff1a;Pinia相比于传统的Vuex&#xff0c;体积更小&#xff0c;性能更好&#xff0c;只有大约1KB左右。 简化API&#xff1a;Pinia简化了状态管理库的使用方法&#xff0c;抛弃了Vuex中的mutations&#xff0c;只保留了state、getters和actions…

科普文:docker基础概念、软件安装和常用命令

docker基本概念 一 容器的概念 1. 什么是容器&#xff1a;容器是在隔离的环境里面运行的一个进程&#xff0c;这个隔离的环境有自己的系统目录文件&#xff0c;有自己的ip地址&#xff0c;主机名等。也可以说&#xff1a;容器是一种轻量级虚拟化的技术。 2. 容器相对于kvm虚…

基于Golang+Vue3快速搭建的博客系统

WANLI 博客系统 项目介绍 基于vue3和gin框架开发的前后端分离个人博客系统&#xff0c;包含md格式的文本编辑展示&#xff0c;点赞评论收藏&#xff0c;新闻热点&#xff0c;匿名聊天室&#xff0c;文章搜索等功能。 项目在线访问&#xff1a;http://bloggo.chat/ 访客账号…

SMU Summer 2024 Contest Round 7

Bouquet 思路&#xff1a; 总的方案数就是C(n,1)C(n,2) . . . . C(n,n) &#xff1b;然后不符合的方案数为C(n,a)C(n,b); 两者相减就是答案&#xff1b;因为算组合数时&#xff0c;数据非常大&#xff0c;所以要用到lucas定理来计算组合数的大小&#xff1b; 当同余定理用…

C#使用Clipper2进行多边形合并、相交、相减、异或的示例

Clipper2库介绍 开源库介绍&#xff1a; Clipper2在Github上的地址&#xff1a;https://github.com/AngusJohnson/Clipper2 Clipper2库对简单和复杂多边形执行交集&#xff08;Intersection&#xff09;、并集&#xff08;Union&#xff09;、差分&#xff08;Difference&…

Python安装

download 1、下载 后直接安装 2、cmd运行命令 python

kafka详解及应用场景介绍

Kafka架构 Kafka架构&#xff0c;由多个组件组成&#xff0c;如下图所示&#xff1a; 主要会包含&#xff1a;Topic、生产者、消费者、消费组等组件。 服务代理&#xff08;Broker&#xff09; Broker是Kafka集群中的一个节点&#xff0c;每个节点都是一个独立的Kafka服务器…

Oracle集群RAC磁盘管理命令asmcmd的使用

文章目录 ASM磁盘共享简介ASM磁盘共享的优势ASM磁盘组成ASM磁盘共享的应用场景Asmcmd简介Asmcmd的功能Asmcmd的命令Asmcmd的使用注意事项Asmcmd运行模式交互模式运行非交互模式运行ASMCMD命令分类实例管理命令:文件管理命令:磁盘组管理命令:模板管理命令:文件访问管理命令:…