vue3点击按钮实现登录 登录完成后继续去页面
时间: 2023-05-24 10:05:48 浏览: 197
以下是一个简单的Vue 3登录示例,用户输入用户名和密码并点击“登录”按钮后可以继续访问页面:
```html
<template>
<div>
<h2>Login</h2>
<form @submit.prevent="handleLogin">
<label>Username:</label>
<input type="text" v-model="username" required>
<br>
<label>Password:</label>
<input type="password" v-model="password" required>
<br>
<button type="submit">Login</button>
</form>
</div>
</template>
<script>
import { reactive } from 'vue'
export default {
setup() {
const state = reactive({
username: '',
password: '',
isLoggedIn: false
})
function handleLogin() {
// Here you would normally send a request to a server to authenticate the user
// For demonstration purposes, we'll just set the isLoggedIn flag to true
state.isLoggedIn = true
}
return { state, handleLogin }
},
watch: {
'state.isLoggedIn'(newValue) {
if (newValue) {
// If the user is logged in, navigate to the home page
this.$router.push('/home')
}
}
}
}
</script>
```
在该示例中,我们使用了Vue 3的`reactive`函数来创建一个响应式的状态对象,其中包括用户名、密码和一个表示用户是否已登录的标志位。当用户点击“登录”按钮时,我们只需将`isLoggedIn`标志位设置为`true`。我们还使用了Vue 3的`watch`函数来监视`isLoggedIn`的变化,并根据其值判断用户是否有权继续访问其他页面。如果用户已登录,我们使用Vue Router的`push`方法将路由导航到主页。