vue3中按钮要是没登录,则进入的是登录页面,要是登录了,按钮变成用户名,且点击进入管理系统页面<div class="login"> <button @click="tohome"> 登录 <i v-if="name == Home">登录</i> </button> </div>
时间: 2023-11-22 12:54:12 浏览: 31
你可以使用 Vue 的条件渲染和路由导航钩子来实现这个功能。首先,在模板中使用 `v-if` 指令根据登录状态来显示不同的按钮内容:
```html
<div class="login">
<button v-if="!isLoggedIn" @click="gotoLogin">登录</button>
<button v-else @click="gotoAdmin">{{ username }}</button>
</div>
```
然后,在 Vue 组件的 JavaScript 中,定义 `data` 属性来保存登录状态和用户名:
```js
export default {
data() {
return {
isLoggedIn: false,
username: ""
};
},
methods: {
gotoLogin() {
// 跳转到登录页面
this.$router.push("/login");
},
gotoAdmin() {
// 跳转到管理系统页面
this.$router.push("/admin");
}
},
mounted() {
// 模拟登录,获取用户名
this.isLoggedIn = true;
this.username = "张三";
}
};
```
最后,在 Vue 路由中使用 `beforeEnter` 钩子来判断是否已登录,并在未登录时跳转到登录页面:
```js
const routes = [
{ path: "/", component: Home },
{ path: "/login", component: Login },
{
path: "/admin",
component: Admin,
beforeEnter: (to, from, next) => {
if (!store.getters.isLoggedIn) {
next("/login"); // 未登录,跳转到登录页面
} else {
next(); // 已登录,继续访问
}
}
}
];
```
这样,当用户点击按钮时,会根据登录状态自动跳转到不同的页面。