路由懒加载
👉 等用户真正访问到某个路由页面时,才去加载对应的组件文件,而不是在应用一开始就把所有路由对应的组件都加载进来。
-
首屏优化 :如果你的项目很大,所有页面组件一次性打包,首屏加载速度会很慢。
-
分包加载 :只加载用户需要的页面,减少初始包体积。
-
体验更流畅 :用户点到新页面时才加载对应的资源,避免不必要的开销。
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
redirect: '/dashboard',
component: () => import('@/views/Layout/index.vue'),
children: [
{
path: 'article',
component: () => import('@/views/Article/index.vue')
},
{
path: 'dashboard',
component: () => import('@/views/Dashboard/index.vue')
}
]
},
{
path: '/login',
component: () => import('@/views/Login/index.vue')
}
]
})<style scoped> 中修改第三方组件的样式不生效的问题
使用 :deep() 包裹第三方组件对应的类,即可做到组件作用域穿透,修改样式:
.el-form-item:last-child {
:deep(.el-form-item__content) {
display: flex;
justify-content: center;
gap: 10px;
}
}请求拦截器的使用
请求拦截可以干以下事情:
- 实现每次请求时候统一带上
token
const instance = axios.create({
baseURL: 'http://localhost:4000/api',
timeout: 1000 // 请求超时时间
});
// 请求拦截器:每次请求发出之前都会经过该拦截器
instance.interceptors.request.use(
(config) => {
// 每次请求带上token(如果有的话)
const token = getToken()
if(token) {
config.headers.Authorization = `Bearer ${token}`
}
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 查键(token.js文件)
export const getToken = () => {
return localStorage.getItem(TOKEN_KEY)
}响应拦截器的使用
响应拦截可以干以下事情:
-
成功处理: 对响应数据进行简化,再返回给调用处
- 举个例子,通过
axios发送网络请求之后拿到的response对象,要拿到里面的token数据时候,可能需要response.data.data.token才能拿到,又臭又长,所以可以在响应拦截器中按需返回response.data.data即可,这样子在响应之后拿到的对象要拿到token就很简单啦~
- 举个例子,通过
-
失败处理: 判断状态码,看看是否为
token失效等情况进行处理
const instance = axios.create({
baseURL: 'http://localhost:4000/api',
timeout: 1000 // 请求超时时间
});
// 响应拦截器:每次响应数据给调用处之前会经过该拦截器
instance.interceptors.response.use(
(response) => {
// 对响应数据进行简化,再返回
const { data:resp } = response
const { code, data, message } = resp
if(code === STATUS_CODE.success) {
return data
}
return Promise.reject(message)
},
(error) => {
// 走到这说明发生了 4xx、5xx 等错误,比如token过期
const { status, data: {message} } = error.response
ElMessage.error(message)
if(status === STATUS_CODE.unauthorized) {
const userStore = useUserStore()
// 清除token
userStore.clearRequest()
// 跳转到登陆页面
router.push(`/login?redirectUrl=${router.currentRoute.value.path}`)
}
return Promise.reject(message);
}
);await 的使用场景
如果函数返回对象是 promise 的话,则说明该函数异步执行 的。
如果要让调用处同步执行,则需要使用 await 修饰,让程序停在这里而不是直接往下面执行~
// 举个例子:获取文章信息
const getArticleData = async (currentPage) => {
try {
// 发起获取文章请求,拿到数据
const data = await articleApi({current: currentPage, pageSize: tableData.pageTotal})
// 只有上面执行完了,才能进行赋值!
tableData.totalItems = data.total
tableData.totalPages = data.pageTotal
tableData.rows = data.rows
} catch(e) {}
}await 的使用问题
下面两种写法本质是一样的,不过后者会更加直观!
const open = () => {
ElMessageBox.confirm(
'proxy will permanently delete the file. Continue?',
'Warning',
{
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
}
)
.then(() => {
ElMessage({
type: 'success',
message: 'Delete completed',
})
})
.catch(() => {
ElMessage({
type: 'info',
message: 'Delete canceled',
})
})
}
等价于
const open = async () => {
try {
await ElMessageBox.confirm(
'proxy will permanently delete the file. Continue?',
'Warning',
{
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
}
)
ElMessage.success('Delete completed') // 走到这说明 ElMessageBox.confirm 成功了
} catch (e) {
ElMessage.info('Delete canceled') // 走到这说明 ElMessageBox.confirm 失败了
}
}利用好模板字符串
模板字符串可以随时使用占位符,实现动态传参!
router.push(`/login?redirectUrl=${router.currentRoute.value.path}`)
export const articleDetailApi = (id) => {
return request({
method: 'get',
url: `/article/${id}`
})
}axios 请求的注意事项
-
GET 请求 :将分页参数放到
params中,适用于 URL 查询字符串 传参 -
POST 请求 :将分页参数放到
data中,适用于 请求体 传参
// 获取文章列表
export const articleApi = (query) => {
return request({
method: 'get',
url: '/article',
params: query
})
}
// 新增文章
export const addArticleApi = (articleForm) => {
return request({
method: 'post',
url: '/article',
data: articleForm
})
}实现登录跳回原地址
请求以及响应拦截时候,可以实现登陆后跳回原先地址(除非一开始访问的是首页而不是其它页面),如下所示:
// 登录验证
router.beforeEach((to, from) => {
// 先从pinia中获取token
const userStore = useUserStore()
const { user_token } = userStore
if(user_token) {
// 如果存在token,则说明已经登录
if(to.path === '/login') {
return '/' // 如果还想去登录,则直接跳转到主页去
} else {
return true;
}
} else {
// 如果不存在token,则说明未登录,判断一下是否为白名单页面
if(whiteList.includes(to.path)) {
return true
} else {
ElMessage.error('请先登录!')
return `/login?redirectUrl=${to.path}` // 重定向到登录页面,并且为了后面登录后能调回来,需要传参
}
}
})其中守卫路由里面 return /login?redirectUrl=${to.path}`` 这句就相当于下面的语法:
router.push({
path: '/login',
query: {
redirectUrl: to.path
}
})抽屉的使用注意事项
在打开抽屉的时候会有一个问题,就是抽屉里面的组件只有在第一次打开的时候进行创建,往后不会再创建,这会导致我们复用的组件 <articleOps> 没办法实现预览抽屉、新增抽屉/编辑抽屉 三个不同界面的切换效果。
解决方法:可以在 <el-drawer>中使用 :key然后传入一个不重复的值,即可保证每次都会创建新的组件实例 。
<!-- 抽屉功能 -->
<el-drawer
v-model="drawer"
:title="articleCurrentOps"
direction="rtl"
size="45%"
:key="articleId" // 保证key不会重复即可
>
<articleOps :opsType="currentOps" :articleId="articleId"/>
</el-drawer>富文本编辑器的使用注意事项
新增/编辑文章之后,需要清空表单输入数据,此时已经把响应式对象清空了,数据确实是空的 。但 QuillEditor 这种富文本编辑器有点特殊:
-
它不是完全受控组件(不像
el-input),内部还有自己的状态。 -
你更新
v-model:content的值为''时,Vue 已经变了,但 Quill 并不会立刻同步刷新内容。 -
解决方法:在
QuillEditor中传入一个 key 属性,传入一个每次清空表单都会变化的变量 ,如下所示:const editorKey = ref(0) // 这个变量用于刷新富文本编辑器的content <QuillEditor :key="editorKey" theme="snow" toolbar="full" placeholder="请输入内容" v-model:content="articleForm.content" contentType="html" />