在router.js中
router.beforeEach((to, from, next) => {
// 1.如果访问的是登录页面(无需权限),直接放行
if (to.path === '/login' || to.path === '/home' || to.path === '/') return next()
// 2.如果访问的是有登录权限的页面,先要获取token
const tokenStr = window.sessionStorage.getItem('token')
// 2.1如果token为空,强制跳转到登录页面;否则,直接放行
if (!tokenStr) {
ElMessage({
message:"请登录",
type:'warning'
})
return next('/login')
}
next()
})
vue3引入element-plus和图标
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElIcon from '@element-plus/icons-vue'
Object.keys(ElIcon).forEach((key) => {
app.component(key, ElIcon[key])
})
app.use(ElementPlus)
app.use(store)
app.use(router)
app.mount('#app')
vue3引入全局axios
import axios from 'axios'
const app = createApp(App)
app.provide('$axios',axios)
Object.keys(ElIcon).forEach((key) => {
app.component(key, ElIcon[key])
})
app.use(ElementPlus)
app.use(store)
app.use(router)
app.mount('#app')
在组件中引入axios
import { inject } from "vue"
const axios = inject('$axios')
let getList = async () => {
let { data } = await axios.get("http://localhost:3000/collection")
console.log(data);
list.value = data.data
}
文章介绍了如何在Vue3项目中配置router.js进行登录验证,引入element-plus库并将其图标全局注册,以及如何使用axios进行API请求并在组件中通过注入方式使用。

被折叠的 条评论
为什么被折叠?



