把握数据模拟的强大武器-深化详解Vue3中的Mock数据模拟 (把握数据模拟方法)
Vue3前端开发时,须要api恳求模拟和数据模拟,我将在接上去的期间写Mock模拟和json-server模拟。两种比拟盛行的形式,如今先引见mock形式。
经常使用NPM装置Mock.js库
Mock.js是一个轻量级的前端数据模拟工具,可以极速生成随机数据,允许自定义数据类型和规定等性能。我们可以经常使用NPM来启动装置。
在命令行中口头以下命令:
npminstallmockjsyarnaddmockjs-D
在Vue名目中性能Mock.js
在Vue名目中经常使用Mock.js须要先引入关系的包,并在名目中启动相应的性能。我们可以先在Vue名目中创立一个mock文件夹,并在该文件夹下新建index.ts文件。在index.ts文件(src/mock/index.ts)中编写以下代码:
importMockfrom'mockjs'//设置阻拦Ajax恳求的照应期间,模拟网络提前Mock.setup({timeout:'200-600'})//Mock数据示例Mock.mock(baseUrl+'/api/getList','get',{'list|10-20':[{'id|+1':1,'title':'@ctitle(10,20)','image':'@image('200x100','#50B347','Hello')','datetime':'@datetime()','author':'@cname()','description':'@ctitle(30,100)'}]})exportdefaultMock
创立http恳求对象src/utils/request.ts
importaxfrom'axios'constservice=axios.create({baseURL:'/ceshi',withCredentials:false,timeout:60000})//恳求阻拦器service.interceptors.request.use(config=>{//...一致修正恳求头returnconfig},error=>{//...网络失误Promise.reject(error)})//照应阻拦service.interceptors.response.use(response=>{returnresponse.data},e=>{returnPromise.reject(e)})exportdefaultservice
创立视图src/views/MockView.vue
<template><div><ul><liv-for="iteminlist":key="item.id"><h5>{{item.tip}}?{{item.content}}</h5></li></ul></div><el-table:data="tableList"><el-table-column/><el-table-column/><el-table-column/><el-table-column/><el-table-column/><el-table-column/></el-table><el-table:data="AuthorList"><el-table-column/><el-table-column/><el-table-column/><el-table-column/><el-table-column><template#default="scope"><el-image:src="scope.row.image"></el-image></template></el-table-column><el-table-column/><el-table-column><template#default><el-buttonlink@click="fun_del">Detail</el-button><el-buttonlink@click="fun_edit">Edit</el-button></template></el-table-column></el-table></template><scriptsetup>import{onMounted,ref}from'vue'importrequestfrom'@/utils/request'typeTArticle={id:number,tip:string,content:string,};interfaceArticle{id:number,tip:string,content:string,};letlist=ref<Array<TArticle>>([]);consttableList=ref([])constAuthorList=ref([])onMounted(()=>{/***/getList().then((res)=>{AuthorList.value=res.list;console.log(res);});getDetail(1).then((res)=>{console.log(res);tableList.value=res.data;}).catch((e)=>{console.error(e)})})constfun_del=(data:any)=>{console.log(data);}constfun_edit=(data:any)=>{console.log(data);}constfun_add=(data:any)=>{console.log(data);}constgetList=async()=>{returnrequest({url:'/api/getList',method:'get'})}functiongetArticles(){returnrequest({url:'/api/article',method:'get'})}functionselectA(val:any){returnrequest({url:'/api/selectArticle',method:'get',>路由src/router/index.ts代码import{createRouter,createWebHistory,createWebHashHistory}from'vue-router'//页面组件经过import引入,假设经常使用懒加载形式则无需在此经过import引入//importHomeViewfrom'../views/HomeView.vue'importHomeViewfrom'../views/HomeView.vue'constrouter=createRouter({//createWebHashHistory(),//history形式则经常使用createWebHistory()history:createWebHashHistory(import.meta.env.BASE_URL),routes:[//组件援用形式有两种,只需选用一种形式即可{path:'/',name:'home',component:HomeView},{path:'/about',name:'about',//routelevelcode-splitting//thisgeneratesaseparatechunk(About.[hash].js)forthisroute//whichislazy-loadedwhentherouteisvisited.component:()=>import('../views/AboutView.vue')},{path:'/mock',name:'mock',component:()=>import('../views/MockView.vue')}]})
修正src/main.ts
import{create}from'vue'import'./style.'importAppfrom'./App.vue'importrouterfrom'./router'importElementPlusfrom'element-plus'import'element-plus/dist/index.css'//importMockfrom'./mock'//引入mock数据import"./mock/index.ts"constapp=createApp(App)app.use(router)//全体引入app.use(ElementPlus,{size:'small',zIndex:3000})app.mount('#app')
修正App.vue文件
<template><div><nav><router-link>home</router-link>|<router-link>mock</router-link>|<router-link>About</router-link></nav></div><Router-view/></template><scriptsetup>//importHelloWorldfrom'./components/HelloWorld.vue'</script><stylescoped>.logo{height:6em;padding:1.5em;will-change:filter;transition:filter300ms;}.logo:hover{filter:drop-shadow(002em#646cffaa);}.logo.vue:hover{filter:drop-shadow(002em#42b883aa);}#app{font-family:Avenir,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-align:center;color:#2c3e50;}nav{padding:30px;a{font-weight:bold;color:#2c3e50;&.router-link-exact-active{color:#42b983;}}}</style>
补充
npminstall-Dunplugin-vue-componentsunplugin-auto-import
//vite.config.tsimport{defineConfig}from'vite'importAutoImportfrom'unplugin-auto-import/vite'importComponentsfrom'unplugin-vue-components/vite'import{ElementPlusResolver}from'unplugin-vue-components/resolvers'exportdefaultdefineConfig({//...plugins:[//...AutoImport({resolvers:[ElementPlusResolver()],}),Components({resolvers:[ElementPlusResolver()],}),],})
成果图
目录结构
package.json文件
{"name":"vue3-vite-ts","private":true,"version":"0.0.0.1","type":"module","scripts":{"dev":"vite","build":"vue-tsc&&vitebuild","preview":"vitepreview","lint":"eslintsrc/**/*.{js,jsx,vue,ts,tsx}--fix"},"dependencies":{"@element-plus/icons-vue":"^2.1.0","axios":"^1.5.0","babel-eslint":"^10.1.0","element-plus":"^2.4.2","http":"^0.0.1-security","js-cookie":"^3.0.5","path":"^0.12.7","pinia":"^2.1.6","pinia-plugin-persistedstate":"^3.2.0","pinia-use-persist":"^0.0.21","qs":"^6.11.2","vite-plugin-svg-icons":"^2.0.1","vue":"^3.3.4","vue-router":"^4.2.4"},"devDependencies":{"@types/js-cookie":"^3.0.4","@types/mockjs":"^1.0.9","@types/node":"^20.6.3","@types/nprogress":"^0.2.0","@types/qs":"^6.9.9","@typescript-eslint/eslint-plugin":"^6.7.2","@typescript-eslint/parser":"^6.7.2","@vitejs/plugin-vue":"^4.2.3","eslint":"^8.49.0","eslint-plugin-vue":"^9.17.0","fast-glob":"^3.3.1","fs":"^0.0.1-security","less":"^4.2.0","less-loader":"^11.1.3","mockjs":"^1.1.0","nprogress":"^0.2.0","sass":"^1.68.0","typescript":"^5.0.2","unplugin-auto-import":"^0.16.7","unplugin-vue-components":"^0.25.2","vite":"^4.4.5","vite-plugin-svg-icons":"^2.0.1","vue-tsc":"^1.8.5"},"rules":{"vue/multi--component-names":"off"}}
接口RAP开源吗?
随着 Web 技术的发展,前后端分离构架变的越来越流行。前后端分离使后端专注于数据处理和定义前端所需要的接口,前端负责数据的展现和交互,大大细化了开发者的职责,提高了开发效率,但与此同时也带来了一些问题:
uniapp 使用mock数据方式总结
1.2019.12.25 uniapp使用了vue, 那开发环境如何mockJS?分为3个步骤 --- 通过封装uniapp的请求函数,然后劫持uniapp的请求。其中用到了装饰者函数。可以做到函数职责单一原则,不需要修改请求函数。 1.封装uniapp request: 如下:
2.装饰者拦截请求:
免责声明:本文转载或采集自网络,版权归原作者所有。本网站刊发此文旨在传递更多信息,并不代表本网赞同其观点和对其真实性负责。如涉及版权、内容等问题,请联系本网,我们将在第一时间删除。同时,本网站不对所刊发内容的准确性、真实性、完整性、及时性、原创性等进行保证,请读者仅作参考,并请自行核实相关内容。对于因使用或依赖本文内容所产生的任何直接或间接损失,本网站不承担任何责任。