In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to configure and use mockjs in vue". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to configure and use mockjs in vue.
Mockjs configuration and usage requirements
In the development of the separation of the front and rear ends, the front and rear ends need to be developed at the same time, but before the completion of the back end, there is no data returned to the front end for use. if you write static first and then change it, there will be internal friction of repeated work.
So we need a simple and fast module to simulate data, this paper chooses mockjs.
Steps
1. Install mockjs
Npm install mockjs
two。 Create a mock folder under the src folder of the project, and create an index.js under the mock folder (storing all the interface data returned by http simulation). I wrote two APIs below:
Import Mock from 'mockjs' 'get', (req, res) = > {return {code: 200, data: {id: 1, sex: 1, age: 25, createTime:' 2017-04-01'}, message: 'query successful'}) export default {vehicle, user}
3. To facilitate the use of mock simulation data in all components to import newly edited interface data in the main.js of the project
Import mockdata from ". / mock"; / / so that the interface can be called at will in the component.
4. Call a virtual interface in a component
Call the interface in the lifecycle hook function: I use axios, provided that the project has installed axios (first npm install axios, then npm install-- save axios vue-axios), a button executes the click event, and the following method adjusts the interface
Click to query methods: {search () {this.$http.get ("/ api/user") .then (res = > {console.log (res);}); this.$http.post ("/ api/car") .then (res = > {console.log (res);});}}
5. Note after the completion of the project interface debugging, you need to delete the references to mock in main.js and the simulation resources such as mock/index.js, so that there is no need to make any changes in the components, and the repeated workload is minimized.
Mock use and mock non-invasive solution what is mock?
After reading the introduction of the official website, for the front-end, "front-end separation" has greatly improved the efficiency of front-end development.
After discussing the requirements, interfaces and data formats, the front-end developers can directly use mock to simulate the data returned by the background for code development.
Why use mock?
Now I'm drawing a flow chart to help you understand the processing logic of mock in the project.
It can be seen that the front end can use the mock service to simulate the request for background data. As long as the interface document comes out, it can simulate the fake data with mock according to the api and data format of the interface document.
How to use mock?
Its use is introduced here with the project of vue-cli2.x scaffolding.
1. Install mockjs npm install-- save-dev mockjs or npm install-D mockjs
two。 Add the mock folder to the root directory src, as shown in the following structure, and create
The content of index.js is:
Import Mock from 'mockjs' import {Service} from'. / data/service' Mock.mock (/\ / Service\ / ServiceList/, 'get', Service) console.log ('% c front-end mock environment started successfully', 'color: # 38f: bold') export default Mock
The service.js in the data folder is the data returned by the mock simulation, which contains:
Import Mock from 'mockjs';const Service = []; for (let I = 0; I
< 5; i++) {Service.push(Mock.mock({ id: Mock.Random.guid(), serviceName: `${Mock.Random.protocol()} --${Mock.Random.id()}`, 'port|8000-9000': 1, ip: Mock.Random.ip(), status: Mock.Random.pick(['passing', 'Critical', 'critical','null']), 'node|0-2': 1 }));}export default Service; 3.在main.js中引入定义的mock文件夹 import Mock from './mock' 此时打开终端控制面板,运行 npm run dev 后,打开开发者调试工具的console,即可看见4. Next, all http requests sent will be intercepted by mock. If they match the url path set in mock / Service/ServiceList, the simulated data of service.js will be returned, as follows (.vue file)
Import axios from "axios"; export default {data () {return {};}, methods: {getServer () {axios. Get ('/ Service/ServiceList') .then ((res) = > {console.log (res);}) .catch ((error) = > {console.log (error);});}},}
As shown in the screenshot above, you can see that the request sent to the url has been matched and intercepted and an object has been returned. You can define an empty array to save the res.data data and render it to the page.
5. If the url that sent the http request does not match or does not exist as defined in mock, an error will pop up
Note: remember that mock will intercept all http requests, including the real API you want to request, and will also intercept and prompt 404 to report an error; just comment out the import Mock from'. / mock' introduced in main.js at this time
However, the motivation of "laziness" makes us think, how can we "ravage" mock as a very obedient thing?
Mock non-intrusive configuration
Then we need to think about how to separate the mock in the project code, which can not only ensure the separate development of the front and rear, but also switch the environment arbitrarily without changing the code.
Everyone should be aware that in the project framework built with vue-cli, there will be directly configured npm run dev and npm run build environments.
When you think of this step, you should also have an idea, that is, configure a set of dev environment, rename it to mock, and later switch the code runtime environment at will through a single instruction of npm run mock and npm run dev.
How can it be realized? Just listen to me in detail (this is the vue@2.5.2 version as an example)
1. Use vue-cli to build the project framework, open the package.json file, and add a running script
"mock": "webpack-dev-server-inline-progress-config build/webpack.mock.conf.js"
As follows:
Do not copy the sentence "start": "npm run dev", "lint": "eslint-- ext .js, .vue src", "build": "node build/build.js"}
two。 Create the webpack.mock.conf.js file in the build folder under the root directory, and copy all the contents of the webpack.dev.conf.js file
3. Add the configuration in webpack.mock.conf.js as follows
After saving, open the terminal and run npm run mock
If you need to debug the interface with the background later, you can switch over by running npm run dev directly to ensure that the mock is extracted from the business code.
Note: once entry is configured in webpack.mock.config.js, there is no need to introduce Mock in main.js.
Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.