Home > Web Front-end > Vue.js > How to use mock to simulate data problems in vite+vue3

How to use mock to simulate data problems in vite+vue3

WBOY
Release: 2023-05-15 08:07:05
forward
2534 people have browsed it

1. Install mockjs and vite-plugin-mock

npm i mockjs vite-plugin-mock --save-dev
Copy after login

2. Configure

vite-plugin-mock usage in the vite.config.ts file

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { viteMockServe } from 'vite-plugin-mock'
 
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(),
    viteMockServe({
      supportTs:false,
      logger: false,
      mockPath: "./mock/"
    })
  ]
})
Copy after login
## The meaning of the configuration content in #vite-plugin-mock

{
supportTs?: boolean; --是否读取ts文件模块,设置为true时不能读取js文件

logger?:boolean; --是否在控制台显示请求日志
mockPath?: string;  --设置模拟数据的存储文件夹,如果不是index.js需要写明完整路径
ignore?: RegExp | ((fileName: string) => boolean);--读取文件时忽略指定格式的文件
watchFiles?: boolean;--是否监视mockPath文件夹内文件的修改
localEnabled?: boolean;--设置是否启用本地 xxx.ts 文件,不要在生产环境中打开它.设置为 false 将禁用 mock 功能
ignoreFiles?: string[]; --读取文件时忽略的文件
configPath?: string;--设置模拟读取的数据条目。 当文件存在并且位于项目根目录中时,将首先读取并使用该文件。 配置文件返回一个数组
prodEnabled?: boolean;--设置打包是否启用 mock 功能
injectFile?: string;--如果生产环境开启了 mock 功能,即prodEnabled=true.则该代码会被注入到injectFile对应的文件的底部。默认为main.{ts,js}。这样做的好处是,可以动态控制生产环境是否开启 mock 且在没有开启的时候 mock.js 不会被打包。如果代码直接写在main.ts内,则不管有没有开启,最终的打包都会包含mock.js

injectCode?: string;--injectCode代码注入的文件,默认为项目根目录下src/main.{ts,js}

}
Copy after login

3. Create a mock folder in the root directory

New folder mock/index.js

export default [{
    type:'get',
    url:'/user/login',
    response: () => {
        return {isAuth:true}
    }
},{
    type:'get',
    url:'/user/menu',
    response: () => {
        return {menusList:[{
            id:'/sysManagent',
            title:'系统管理',
            subMenuList:[
                {
                    id:'/userList',
                    title:'用户管理',
                    path:'/user/manage'
                },
                {
                    id:'/roleList',
                    title:'角色管理',
                    path:'/user/role'
                },
                {
                    id:'/permissionList',
                    title:'权限管理',
                    path:'/user/permission'
                }
            ]
        },{
            id:'businessManagent',
            title:'业务管理',
            subMenuList:[
                {
                    id:'/businessList',
                    title:'业务逻辑'
                }
            ]
        }],statusCode:200}
    }
}]
Copy after login

4. Call

<template>
  <div class="aside">
    <div class="collpase-btn" @click="collpaseMenu">
      <el-icon><fold /></el-icon>
    </div>
    <el-menu
      active-text-color="#ffd04b"
      background-color="#545c64"
      class="el-menu-vertical-demo"
      :default-active="router.path"
      text-color="#fff"
      :collapse="store.state.isCollapse"
      @open="handleOpen"
      @close="handleClose"
      :router="true"
    >
      <el-sub-menu
        :index="item.id"
        v-for="item in menus.mensList"
        :key="item.id"
      >
        <template #title>
          <el-icon><grid /></el-icon>
          <span>{{ item.title }}</span>
        </template>
        <el-menu-item :index="it.id" v-for="it in item.subMenuList">
          {{ it.title }}
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>
<script lang="ts">
import axios from &#39;axios&#39;
import { defineComponent, onMounted, reactive } from &#39;vue&#39;
import { useRoute } from &#39;vue-router&#39;
import { useStore } from &#39;vuex&#39;
 
export default defineComponent({
  name: &#39;Aside&#39;,
  setup() {
    const store = useStore()
    const router = useRoute()
    const mensList: any = []
    let menus = reactive({ mensList })
 
    const handleOpen = (key: string, keyPath: string[]) => {}
    const handleClose = (key: string, keyPath: string[]) => {}
    const collpaseMenu = () => {
      store.dispatch(&#39;collpaseChange&#39;)
    }
    onMounted(() => {
      axios.get(&#39;/user/menu&#39;).then((res) => {
        console.log(res);
        menus.mensList = res.data.menusList
      })
    })
    return {
      handleOpen,
      handleClose,
      collpaseMenu,
      store,
      menus,
      router
    }
  },
})
</script>
 
<style lang="scss" scoped>
.el-menu-item.is-active {
  background-color: var(--el-menu-hover-bg-color);
}
.collpase-btn {
  text-align: center;
  width: 100%;
  padding: 10px 0px;
  cursor: pointer;
  .el-icon {
    color: white;
    font-size: 24px;
  }
}
</style>
Copy after login

How to use mock to simulate data problems in vite+vue3

in the file. 5. Others

If the mock folder is built in the src file directory, you need to modify the tsconfig.json file

"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue","src/mock/**/*.ts"],
Copy after login

The above is the detailed content of How to use mock to simulate data problems in vite+vue3. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template