Home > Web Front-end > Vue.js > body text

How to use mockjs to randomly simulate data in Vue3+Vite project

WBOY
Release: 2023-05-14 10:01:05
forward
2314 people have browsed it

在vite中使用mockjs进行模拟数据,需要借助新的依赖进行使用

一、安装mockjs

yarn add mockjs -S 或 npm i mockjs -D
Copy after login

二、安装vite-plugin-mock

npm i vite-plugin-mock -D
Copy after login

三、在src/mock/source文件夹下创建user.ts

How to use mockjs to randomly simulate data in Vue3+Vite project

在index.vue中放入以下内容:

import { MockMethod } from 'vite-plugin-mock'

export default [
  {
    url: '/api/getUserInfo', // 注意,这里只能是string格式
    method: 'get',
    response: () => {
      return {
        menusList: [{
          id: '1',
          title: '南辰',
          subMenuList: [
            {
              id: '11',
              title: '南',
              path: '/user/nan'
            },
            {
              id: '12',
              title: '小',
              path: '/user/xiao'
            },
            {
              id: '13',
              title: '辰',
              path: '/user/chen'
            }
          ]
        }, {
          id: '2',
          title: '希',
          subMenuList: [
            {
              id: '21',
              title: '玩游戏',
              path: '/user/play'
            }
          ]
        }]
      }
    }
  }
] as MockMethod[] // 这里其实就是定义数据格式的,不了解的同学可以参考typescript的官方文档
Copy after login

四、开发环境配置

如果只是本地开发环境时使用,直接看下面即可步骤

在vite.config.ts进行个人配置

import { viteMockServe } from 'vite-plugin-mock'

export default defineConfig({
  plugins: [
    viteMockServe({
      mockPath: "./src/mock/source", // 解析刚刚user.ts的位置
      localEnabled: true // 是否开启开发环境
    })
  ]
})
Copy after login

在页面中引入

<template>
  <div>{{name.name}}</div>
  <div>{{nc}}</div>
</template>

<script lang=&#39;ts&#39;>
import { useRoute } from "vue-router"; //引入路由组件
import { onMounted, ref } from "vue";
import axios from "axios";
export default {
  setup() {
    const nc = ref("");
    onMounted(() => {
      axios.get("/api/getUserInfo").then((res) => {
        console.log(res);
        nc.value = res.data.menusList[0].title;
        console.log(nc.value);
      });
    });
    const $route = useRoute();
    const name = $route.query;
    return {
      name,
      nc,
    };
  },
};
</script>
<style scoped>
</style>
Copy after login

打印效果如下:
How to use mockjs to randomly simulate data in Vue3+Vite project

如果想使用随机数可以看接下来的步骤

如果只要随机数则直接生成即可
How to use mockjs to randomly simulate data in Vue3+Vite project
How to use mockjs to randomly simulate data in Vue3+Vite project

想要随机数在return中放入随机条件即可。

如果想要用随机数中的图片就需要从mockjs中引入一个Random方法
How to use mockjs to randomly simulate data in Vue3+Vite project
在页面上进行循环:

<template>
  <div v-for="(item,index) in list" :key="index">
   <img :src="item.image" alt="">
   <p>{{item.id}}</p>
  </div>
</template>

<script lang=&#39;ts&#39;>
import { useRoute } from "vue-router"; //引入路由组件
import { onMounted, ref } from "vue";
import axios from "axios";
export default {
  setup() {
    const list = ref("");
    onMounted(() => {
      axios.get("/api/getUserInfo").then((res) => {
        console.log(res);
        let lis = res.data.list;
        console.log(list.value =lis);
      });
    });

    return {
      nc,
      list,
    };
  },
};
</script>
<style scoped>
</style>
Copy after login

这里的Random.image()方法是从官网上拿下来用的
How to use mockjs to randomly simulate data in Vue3+Vite project
效果如下:
How to use mockjs to randomly simulate data in Vue3+Vite project

实现随机不同的图片+字段

import { MockMethod } from &#39;vite-plugin-mock&#39;
export default [
  {
    url: &#39;/api/getUserInfo&#39;, // 注意,这里只能是string格式
    method: &#39;get&#39;,
    response: () => {
      return {
        &#39;list|1-10&#39;: [{
          // 属性 id 是一个自增数,起始值为 1,每次增 1
          &#39;id|+1&#39;: 1,
        /*   image: Random.image() */
        "title": "@ctitle",
        "color":&#39;@color&#39;,
        "image":"@image(&#39;&#39;,&#39;@color&#39;)"
        }],
      }
    }
  }
] as MockMethod[]
Copy after login

index.vue

<template>
<div v-for="(item,index) in list" :key="index">
 <img :src="item.image" alt="">
 {{item.title}}
 </div>
</template>

<script lang=&#39;ts&#39;>
import { useRoute } from "vue-router"; //引入路由组件
import { onMounted, ref } from "vue";
import axios from "axios";

export default {
  setup() {
    const list = ref("");
    onMounted(() => {
      axios.get("/api/getUserInfo").then((res) => {
        console.log(res);
        let lis = res.data.list;
        console.log(lis);
        console.log(list.value = lis);
      });
    });
    return {
      list,
    };
  },
};
</script>
<style scoped>
</style>
Copy after login

How to use mockjs to randomly simulate data in Vue3+Vite project
效果如下:
How to use mockjs to randomly simulate data in Vue3+Vite project

The above is the detailed content of How to use mockjs to randomly simulate data in Vue3+Vite project. 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