In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly shows you how "vue-cli realizes asynchronous request to return mock simulation data", the content is simple and easy to understand, and the organization is clear. I hope it can help you solve your doubts. Let Xiaobian lead you to study and learn this article "vue-cli realizes asynchronous request to return mock simulation data".
In the process of front and back end separation development, in the process of front end development, the data display of the page is generally static data written dead, that is, it is written directly in the code without passing through the interface. After the interface is given at the back end, it is replaced with interface data. In order to reduce the docking cost, mock appears. Through the pre-agreed interface with the server side, the simulation request data and even logic can make the front-end development more independent and will not be blocked by the server-side development.
There are many articles on the Internet that use mockjs to simulate data, but basically all of them are local interception requests to return data, and no requests are issued in the network. Local debugging is very bad, and can only be debugged through console.log. In order to achieve true asynchronous request, then you need a real server interface, and in the development of vue-cli project, local development runs the startup command, actually started a local server, then as long as the interface address is configured in the local server and use mock to return data can achieve true asynchronous request, so debugging and real request exactly the same.
began to achieve
Since this is a vue-cli project, install node and npm first.
First, you need to install vue-cli globally:
First, you need to install vue-cli globally:
> npm install -g @vue-cli
2. Create a vue-cli project:
> vue create vue-mock
After successful creation, enter the project root directory, run npm run serve to start, and you should be able to successfully access the vue sample page.
The versions used in this example are vue-cli 4.5.13, vue3, webpack4. If you find that a configuration does not work, please note whether it has been deprecated.
3. Install axios
> npm install axios -S
4, main.js Add aixos, modify as follows
// main.jsimport { createApp } from 'vue'import App from './ App.vue'import axios from 'axios'const vueApp = createApp(App)vueApp.config.globalProperties.$ axios = axios // vue3 differs from vue2, no longer via prototypeApp.mount ('#app')
5. Install mockjs
> npm install mockjs -D
6. Create a mock folder in the root directory, create an index.js file under the mock folder, and introduce index.js in main.js. The code is as follows:
// mock/index.jsimport Mock from 'mockjs'Mock.mock('/url', 'get', (req, res) => { return Mock.mock({ status: 200, req, res, data: 'request successful'})})// main.jsimport { createApp } from 'vue'import App from './ App.vue'import axios from 'axios'import '../ mock/index' //introduce mock route interceptor const vueApp = createApp(App)vueApp.config.globalProperties.$ axios = axiosvueApp.mount('#app')
7. Modify the helloWorld.vue file as follows:
// helloWorld.vue Get mock data export default { name: 'HelloWorld', methods: { getMockData() { this.$ axios.get('/url').then(res => { console.log(res) }) } }}
At this point the page looks like this:
At this point, it can be said that the mock data has been successfully returned. Careful friends may have found that there is no request in the network. We can only view the returned result through the console. When the number of requests is large, it is not easy to debug. Is there any way to make the request appear in the network?
As mentioned earlier, when running the project, it is to start a local server, as long as you find a way to configure the interface route, and then look down
9. Modify the devServer configuration in vue.config.js. If there is no such file, create a new one.
// vue.config.jsconst Mock = require('mockjs')module.exports = { //... devServer: { port: 8082, before: function(app, server) { // webpack4 uses before, webpack uses setupMiddlewares app.get('/url', function(req, res) { res.json(Mock.mock({ status: 200, data: 'Request succeeded ~' })); }); } }};
Comments mock configuration introduced in main.js
import { createApp } from 'vue'import App from './ App.vue'import axios from 'axios'// import '../ mock/index' //introduce mock route interceptor const vueApp = createApp(App)vueApp.config.globalProperties.$ axios = axiosvueApp.mount('#app')
Restart the service, click the button again, the request succeeds, and the request also appears in the network, as shown in the following figure
这样似乎已经实现了我们的目的了,既使用了mock模拟数据,也方便了调试,但是,在我们修改了返回的数据内容时,请求接口,发现还是原来的数据,因为是修改配置文件,所以每次修改都需要重启服务,这也太麻烦了吧,我们想每次修改before里的内容时,服务器都能够自动热更新,就像修改其他文件一样,浏览器自动更新,继续往下走。
10、安装chokidar插件,监听mock文件夹,实现接口路由热更新,想了解更多chokidar的内容请自行搜索
> npm install chokidar -D
11、在mock文件夹下新建mock-server.js,内容如下,就不具体细说了,大家可以自行调试
// mock/mock-server.jsconst chokidar = require('chokidar')const path = require('path')const mockDir = path.join(process.cwd(), 'mock')// 删除对应的接口路由缓存function removeRegisterRoutes() { Object.keys(require.cache).forEach(i => { if (i.includes(mockDir)) { console.log(i) delete require.cache[require.resolve(i)] } })}// 注册接口路由,每增加一个路由,app._router.stack就增加一个堆栈function registerRoutes(app){ const mocks = require('./index') // 这里必须在函数内引用,否则无法实现热更新 let count = 0 for (const mock of mocks) { app[mock.method](mock.url, mock.response); count++ } return { start: app._router.stack.length - count, count }}module.exports = (app) => { let { start, count } = registerRoutes(app) chokidar.watch(mockDir, {}).on('all', (event, path) => { if (event === 'change' || event === 'add') { app._router.stack.splice(start, count) // 先删除旧的api路由,再重新注册新的路由 removeRegisterRoutes() const stack = registerRoutes(app) start = stack.start count = stack.count } })}
注意,修改mock-server.js文件内容不会触发自动更新,具体原因这里就不说了,可以自己想一想哦~
12、修改mock中的index.js文件
// mock/index.jsconst Mock = require('mockjs')const routers = [ { url: '/url', method: 'get', response: (req, res) => { res.json(Mock.mock({ status: 200, data: '请求成功~' })) } }, { url: '/url/path', method: 'get', response: (req, res) => { res.json(Mock.mock({ status: 200, data: '请求接口/url/path' })) } }]module.exports = routers
13、修改vue.config.js的beforte
// vue.config.js// const Mock = require('mockjs')module.exports = { //... devServer: { port: 8082, before: require('./mock/mock-server') }};
重新启动,点击按钮,请求成功,修改mock中的index里面的返回数据,回到页面点击按钮,发现返回数据已改变,到此,已实现接口请求返回mock数据。
以上是"vue-cli如何实现异步请求返回mock模拟数据"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.