vue 用户功能实现
用户登录功能实现
使用 Vue 和 Vuex 管理用户登录状态,结合后端 API 进行身份验证。
模板部分
<template>
<div>
<input v-model="username" placeholder="用户名" />
<input v-model="password" type="password" placeholder="密码" />
<button @click="login">登录</button>
<p v-if="error">{{ error }}</p>
</div>
</template>
脚本部分
<script>
import { mapActions } from 'vuex';
export default {
data() {
return {
username: '',
password: '',
error: '',
};
},
methods: {
...mapActions(['loginUser']),
async login() {
try {
await this.loginUser({ username: this.username, password: this.password });
this.$router.push('/dashboard');
} catch (err) {
this.error = '登录失败,请检查用户名或密码';
}
},
},
};
</script>
用户注册功能实现
通过表单提交用户注册信息,调用后端 API 完成注册流程。
模板部分
<template>
<div>
<input v-model="form.username" placeholder="用户名" />
<input v-model="form.email" placeholder="邮箱" />
<input v-model="form.password" type="password" placeholder="密码" />
<input v-model="form.confirmPassword" type="password" placeholder="确认密码" />
<button @click="register">注册</button>
<p v-if="error">{{ error }}</p>
</div>
</template>
脚本部分

<script>
import { mapActions } from 'vuex';
export default {
data() {
return {
form: {
username: '',
email: '',
password: '',
confirmPassword: '',
},
error: '',
};
},
methods: {
...mapActions(['registerUser']),
async register() {
if (this.form.password !== this.form.confirmPassword) {
this.error = '两次输入的密码不一致';
return;
}
try {
await this.registerUser(this.form);
this.$router.push('/login');
} catch (err) {
this.error = '注册失败,请检查输入信息';
}
},
},
};
</script>
用户信息管理
使用 Vuex 存储用户信息,通过 API 获取或更新用户数据。
Vuex Store 配置
const store = new Vuex.Store({
state: {
user: null,
},
mutations: {
SET_USER(state, user) {
state.user = user;
},
},
actions: {
async fetchUser({ commit }) {
const response = await axios.get('/api/user');
commit('SET_USER', response.data);
},
async updateUser({ commit }, userData) {
const response = await axios.put('/api/user', userData);
commit('SET_USER', response.data);
},
},
});
组件中调用用户信息

<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['user']),
},
created() {
this.fetchUser();
},
methods: {
...mapActions(['fetchUser', 'updateUser']),
async saveProfile() {
await this.updateUser(this.user);
},
},
};
</script>
用户权限控制
通过路由守卫实现页面访问权限控制,未登录用户重定向到登录页。
路由配置
const router = new VueRouter({
routes: [
{ path: '/login', component: Login },
{ path: '/dashboard', component: Dashboard, meta: { requiresAuth: true } },
],
});
router.beforeEach((to, from, next) => {
const isAuthenticated = store.state.user !== null;
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login');
} else {
next();
}
});
用户注销功能
清除 Vuex 中的用户状态并重定向到登录页。
注销方法实现
methods: {
logout() {
this.$store.commit('SET_USER', null);
this.$router.push('/login');
},
}






