vue3.0+mockjs+element Plus模拟登录
在Vue 3.0项目中使用Mock.js和Element Plus进行登录模拟,你可以按照以下步骤操作:
- 安装Mock.js和Element Plus(如果还没安装的话):
npm install mockjs @element-plus/icons-vue --save-dev
npm install element-plus --save
- 在项目中创建一个
mock
文件夹,并添加mockServiceWorker.js
文件。 - 使用Mock.js模拟登录接口:
// mockServiceWorker.js
import { Mock } from 'mockjs'
Mock.mock('/api/login', (options) => {
const { username, password } = JSON.parse(options.body)
if (username === 'admin' && password === '123456') {
return {
code: 200,
message: '登录成功',
// 模拟返回的token
data: { token: 'abcdefg' }
}
} else {
return {
code: 401,
message: '用户名或密码错误',
data: null
}
}
})
- 在
main.js
中引入Mock.js并启动:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import './mock/mockServiceWorker' // 启动Mock
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
- 创建登录组件
Login.vue
并实现登录功能:
<template>
<el-form :model="loginForm" :rules="rules" ref="loginFormRef">
<el-form-item prop="username">
<el-input v-model="loginForm.username" placeholder="用户名"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input type="password" v-model="loginForm.password" placeholder="密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">登录</el-button>
</el-form-item>
</el-form>
</template>
<script>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'
export default {
setup() {
const loginFormRef = ref(null)
const loginForm = ref({
username: 'admin',
password: '123456'
})
const rules = ref({
username: [
{ required: true, message: '请输入用户名', trigger: 'blur' }
],
password: [
{ required: true, message: '请输入密码', trigger: 'blur' },
{ min: 6, max: 12, message: '密码长度在 6 到 12 个字符', trigger: 'blur' }
]
})
const submitForm = () => {
loginFormRef.value.validate((valid) => {
if (valid) {
axios.post('/api/login', loginForm.value)
.then(response => {
if (response.data.code === 200) {
ElMessage.success('登录成功
评论已关闭