使用vue实现根据登录用户不同登录不同界面的代码
时间: 2023-05-18 17:02:43 浏览: 219
vue 实现用户登录方式的切换功能
可以使用Vue的路由功能来实现根据登录用户不同显示不同界面的功能。具体实现步骤如下:
1. 在Vue项目中安装vue-router插件。
2. 在main.js中引入vue-router,并配置路由。
3. 在路由配置中定义需要登录才能访问的页面,并设置路由守卫。
4. 在登录成功后,根据用户角色跳转到不同的页面。
下面是一个简单的示例代码:
// main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
// router.js
import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Admin from './views/Admin.vue'
import User from './views/User.vue'
Vue.use(Router)
const router = new Router({
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/admin',
name: 'admin',
component: Admin,
meta: {
requiresAuth: true,
roles: ['admin']
}
},
{
path: '/user',
name: 'user',
component: User,
meta: {
requiresAuth: true,
roles: ['user']
}
}
]
})
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('isAuthenticated')
const userRole = localStorage.getItem('userRole')
if (to.matched.some(record => record.meta.requiresAuth)) {
if (!isAuthenticated) {
next({
path: '/',
query: { redirect: to.fullPath }
})
} else if (to.meta.roles && !to.meta.roles.includes(userRole)) {
next({ path: '/' })
} else {
next()
}
} else {
next()
}
})
export default router
// Home.vue
<template>
<div>
<h1>Home Page</h1>
<button @click="login('admin')">Admin Login</button>
<button @click="login('user')">User Login</button>
</div>
</template>
<script>
export default {
methods: {
login(role) {
localStorage.setItem('isAuthenticated', true)
localStorage.setItem('userRole', role)
this.$router.push({ name: role })
}
}
}
</script>
// Admin.vue
<template>
<div>
<h1>Admin Page</h1>
<button @click="logout">Logout</button>
</div>
</template>
<script>
export default {
methods: {
logout() {
localStorage.removeItem('isAuthenticated')
localStorage.removeItem('userRole')
this.$router.push({ name: 'home' })
}
}
}
</script>
// User.vue
<template>
<div>
<h1>User Page</h1>
<button @click="logout">Logout</button>
</div>
</template>
<script>
export default {
methods: {
logout() {
localStorage.removeItem('isAuthenticated')
localStorage.removeItem('userRole')
this.$router.push({ name: 'home' })
}
}
}
</script>
阅读全文