Vue3: How to successfully install Mockjs in VSCode and the detailed process of successfully introducing Mock

Ⅰ. MockIntroduction:

1. What is it Mock?

First, Mockthe explanation one:

MockMockService refers to replacing some complex (or not well-structured) objects with a virtual object during the test process; for the front-end, it is the path or definition that the front-end can pass through before the background data is created. Wait, get the desired data format directly;

Second, the Mocksecond explanation:

MockTesting is simulating real object behavior in a controlled way. Programmers usually create simulated objects to test the behavior that the object itself should have, much like car designers use crash test dummies to simulate the dynamic behavior of people in vehicle collisions;

2. Why use it Mock?

First, I think Mockthe role of is:

Front-end development often depends on the back-end data interface. Before the back-end interface is ready to return data, the front-end is usually difficult to start; the Mockfunction is often used to solve data simulation problems. MockAfter having tools to simulate data, the front-end and back-end can enter development simultaneously and improve the team. R&D efficiency.

Ⅱ. Vue3Introduce in the project Mock:

1. Install Mockwith vite-plugin-mock(插件):

First, the installation command is:

npm i mockjs vite-plugin-mock --save-dev

Second, the version is:mockjs: 1.1.0; vite-plugin-mock: 2.9.6;

insert image description here

2. Installation axiosdepends on:

// In general, mockit is axiosused in conjunction with because it is used axiosto call the address;

First, the installation command is:

npm i axios

Second, the version is:axios: 1.3.2;

insert image description here

3. vite.config.jsConfigure vite-plugin-mockand other information in the file

First, the code is:


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

 plugins: [vue(),
    viteMockServe({
    
    
      supportTs:false,
      logger: false,
      mockPath: "./mock/"   // 注意:此时的 mockPath 地址是真正安装的 mock 文件夹的地址;
    })
  ]

// 在配的 viteMockServe({}) 中属性说明:

supportTs?: boolean; --是否读取ts文件模块,设置为true时不能读取js文件
logger?:boolean; --是否在控制台显示请求日志
mockPath?: string; --设置模拟数据的存储文件夹,如果不是index.js需要写明完整路径

Second, vite.config.jsthe code in the file is:

insert image description here

Third, vitethe configuration documents and mockjsthe official documents:

A. viteConfiguration document address:

https://vitejs.dev/config/

insert image description here

B. mockjsThe official document:

http://mockjs.com/examples.html

insert image description here

4. Create mocka folder:

mockFirst, create folders and files in the root directory index.js:

Second, mockthe directory structure after creating the folder:

insert image description here

Ⅲ. Configure the information mockunder the file index.jsand generate relevant data:

1. index.jsThe code in is:

// MockGrammar problem: refer to the official document;


// 引入: mockjs 模块;
import Mock from 'mockjs'

// 内存模拟数据
const arr = []
// 循环 10 次,push 10 个对象;
for(let i =0; i < 10; i++) {
    
    
  arr.push({
    
    
    id: Mock.mock('@guid'),
    name: Mock.mock('@cname'),
    place: Mock.mock('@county(true)'),
  })
}

// 下面是导出一个数组;
export default [
  // 简单模拟一个接口:若是 '/list' 请求,那么就会返回一个 arr;
  {
    
    
    // 发现不需要什么参数,get 方法,地址是 /list;
    url:'/list',         // 表示:请求的地址;
    method: 'get',       // 表示:请求的方式;
    response: () => {
    
    
      return arr
    }
  },
  {
    
    
    url:'/del',
    method: 'delete',
    response: ({
     
     query}) => {
    
    
      const index = arr.findIndex((item) => item.id === query.id)
      arr.splice(index,1)
      return {
    
     sucess: true }
    }
  },
]

2. Access according to the address export defaultin url:

'/list'// At this time, it is added after the accessed address url 地址;

// At this time, it also means that it has been successfully used Mock, and the desired data information has been generated;

insert image description here

3. MockThe process of calling in the page:

First, the code is:

<script setup>
  
  import {
    
     ref } from 'vue'
  import axios from 'axios'

  const list = ref([])
  
  // 发请求肯定要用到 axios, 因此需要引入 axios;
  const getList = async ()=> {
    
    
    
    const r = await axios.get('/list')  // 因为在 mock 的 index.js 里面,发现了一个不需要什么参数,get 方法,地址是 /list 的输出;
                        // 因为这个项目是:在服务器的环境下,因此可以不加域名;
                        // 因为是异步的,因此需要用 async 和 await;
    console.log(r);
  }

  // vue3 在组合式 api 的环境下,没有 created() 这个函数,因此可以直接在 setup 里面调用函数;
  getList()

</script>

Second, the page display results are:

insert image description here

Ⅳ. Summary:

First, where there is something wrong or inappropriate, please give me some pointers and exchanges!
Second, if you are interested, you can pay more attention to this column (Vue (Vue2+Vue3) interview must-have column):https://blog.csdn.net/weixin_43405300/category_11525646.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_43405300/article/details/131511137