本地json通过mock引入至vue中使用

最近练vue项目,没有后端接口,找了本地json实现城市页面,网上找了很多种方法都乱七八糟的,这里重新记录一个踩完坑的方法

首先安装mock :npm install mockjs --save-dev

1、在src文件夹下新建mock文件夹,在此文件夹新建index.js文件

2、main.js引入mock文件夹下的index.js文件

import './mock/index'

3、index.js文件引入mock,引入本地json

import Mock from 'mockjs'
import city from '../../public/json/city.json'

4、使用mock模拟后台数据'/city.php'随便写一个显示后台页面,

Mock.mock('/city.php', 'get', () => {
  return city
})

5、在需要引用json文件下测试

 mounted(){
    axios.get('/city.php').then((res)=>{
      console.log(res)
    })
  }

6、没有了,哦也成功!

原文地址:https://www.cnblogs.com/q582141490/p/13554416.html