本文主要是介绍Vite+Vue3使用MockJS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在使用Vue3开发的时候,有时候没有后端或者后端接口还没有准备好,那就需要使用Mock模拟数据便于前端开发。
现在就记录一下Vite+Vue3的环境下如果使用MockJS。
版本
- vue 3.3.11
- mockjs 1.1.0
- axios 1.6.3
Mockjs配置使用
使用pnpm命令安装Mockjs
pnpm install axios
pnpm install mockjs
mock模拟接口
在src
目录下新建文件夹mock
,并新建文件index.ts
,引入mockjs
import Mock from 'mockjs'
直接在上面引入,在vscode中会报错
找不到模块“mockjs”或其相应的类型声明。ts(2307)
我是使用pnpm、vite新建的vue3项目,只需要在src
目录下的vite-env.d.ts
文件下,加入以下配置即可
/// <reference types="vite/client" />declare module 'mockjs'
main文件下引入mockjs
在main.ts
文件下引入mockjs
import './mock/index'
编写模拟接口
import Mock from 'mockjs'Mock.mock("/mock/login","post", {code: 200, token:"login success token"});Mock.mock("/mock/getGoodsList","get", {code: 200, message:"请求成功",data:[{id:1,introduce:"旺仔牛奶很好喝!!!",title:"旺仔牛奶",userId:1},{id:2,introduce:"旺旺碎碎冰很冰很好吃!!!",title:"旺旺碎碎冰",userId:1},{id:3,introduce:"喜之郎品牌很好吃!!!",title:"喜之郎",userId:1},{id:4,introduce:"卫龙辣条很好吃!!!",title:"卫龙辣条",userId:1},{id:5,introduce:"德芙巧克力很好吃!!!",title:"德芙巧克力",userId:1},{id:6,introduce:"伊利牛奶很好喝!!!",title:"伊利牛奶",userId:1}]
});
axios配置使用
配置axios
import axios from 'axios'//创建axios实例
const service = axios.create({baseURL:"/mock",timeout:5000,headers:{"Content-Type":"application/json;charset=utf-8"}
})//请求拦截
service.interceptors.request.use((config)=>{config.headers=config.headers || {}if(localStorage.getItem("token")){config.headers.token = localStorage.getItem("token") || ""}return config
})// 响应拦截
service.interceptors.response.use((res)=>{const code:number = res.data.codeif(code != 200){return Promise.reject(res.data)}return res
},(err)=>{console.log(err)
})export default service
编写axios的请求接口
import service from ".";
import { LoginData } from "../type/login";//登录接口
export function login(data:LoginData) {return service({url:"/login",method:"post",data})
}//获取商品接口
export function getGoodsList(){return service({url:"/getGoodsList",method:"get",})
}
页面中使用axios请求接口
<template><div class="login-box"><div class="login-box"><el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="80px"class="login-ruleForm"><h2>后台管理系统</h2><el-form-item label="账号:" prop="username"><el-input v-model="ruleForm.username" autocomplete="off" /></el-form-item><el-form-item label="密码:" prop="password"><el-input v-model="ruleForm.password" type="password" autocomplete="off" /></el-form-item><el-form-item><el-button class="loginBtn" type="primary" @click="submitForm(ruleFormRef)">登录</el-button><el-button class="loginBtn" @click="resetForm">重置</el-button></el-form-item></el-form></div></div>
</template><script lang="ts" setup>
import { reactive,ref } from 'vue';
import { LoginData } from '../type/login';
import type { FormInstance } from "element-plus";
import { login } from "../request/api";
import { useRouter } from "vue-router";const ruleForm = reactive<LoginData>({username:"",password:""});const rules = {username: [{required: true,message: "请输入你的账号",trigger: "blur",},{min: 3,max: 10,message: "账号的长度在3到10之间",trigger: "blur",},],password: [{required: true,message: "请输入你的密码",trigger: "blur",},{min: 3,max: 10,message: "密码的长度在3到10之间",trigger: "blur",},],};const resetForm = () => {ruleForm.username = "";ruleForm.password = "";};const ruleFormRef = ref<FormInstance>();const router=useRouter()//-->$routerconst submitForm = (formEl: FormInstance | undefined) => {if (!formEl) return;// 对表单的内容进行验证// valid布尔类型,为true表示验证成功,反之formEl.validate((valid) => {if (valid) {// console.log("submit!");login(ruleForm).then((res) => {console.log(res);// 将token进行保存localStorage.setItem("token", res.data.token);// 跳转页面,首页router.push('/')});} else {console.log("error submit!");return false;}});// console.log(formEl);};
</script><style lang="scss" scoped>
.login-box {width: 100%;height: 100%;background: url('../assets/bg.jpg');padding: 1px;.login-ruleForm{width: 500px;margin: 200px auto;background-color: #fff;padding: 40px;border-radius: 20px;}.loginBtn {width: 48%;}h2 {margin-bottom: 10px;}
}
</style>
这篇关于Vite+Vue3使用MockJS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!