In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the vue cli4 mockjs in the dev environment and build environment how to configure the relevant knowledge, the content is detailed and easy to understand, simple and fast operation, with a certain reference value, I believe that after reading this vue cli4 mockjs in the dev environment and build environment how to configure the article will have a harvest, let's take a look.
Mockjs is configured in dev and build environment configuration in cli4
By default, Vue cli has three development modes: development,production,test.
Custom configuration environment
When cli4 customizes the configuration environment, it needs to add its own files, like this:
These two files are the configuration files for the development environment (.env.development) and production environment (.env.production) that I want to customize.
.env.development:
NODE_ENV='development'// note that the custom variable name must be preceded by VUE_APP_. If you want to get the custom variable here in the project, you can use process.env. For example, if you want to print the url defined below in mainjs, you can use window.console.log (process.env.VUE_APP_URL) VUE_APP_URL = 'http://xxxx.xxx.xx.xxx:xxxx' / / this is the address requested by the interface in the development environment VUE_APP_MOCK = true / / this is to add the mockjs module to the development environment, and the true or flase set here will be written in the mockjs below. You don't have to add this line if you don't use mockjs in your project.
.env.production:
NODE_ENV='production'VUE_APP_URL =''VUE_APP_MOCK = false
Now that we're done with it, all we need is package.json configuration!
Package.json:
"scripts": {"dev": "vue-cli-service serve-- mode development", / / dev is a custom name for the development environment, write it casually, and add this name after npm run. Here, the development after mode is the value of VUE_APP_MODE in the .env.development file above. Running dev environment directly npm run dev "serve": "vue-cli-service serve", "build": "vue-cli-service build-- mode production", "lint": "vue-cli-service lint"}
Run dev environment: npm run dev
/ / for theoretical knowledge, see below. If you simply want to achieve the function, this part can be ignored.
.env / / is loaded in all environments .env.local / / is loaded in all environments, but is ignored by git. [mode] / / is only loaded in the specified mode. Env.[ mode] .local / / is loaded only in the specified mode, but ignored by git
What I understand here is that when running the program, the order of execution is .env (all environments)-> .env. [mode] (specific environment). For example, when running the development environment, npm run dev, the order of execution: first. Env then. Env. Development.
I guess this .env is the serve/build after vue-cli-service in every mode in package.json-scripts, but I have no proof! If you have any knowledge, please ask me! )
Configuration and use of mockjs in vue cli4 Development Environment
1. Install mockjs
Go to the project folder, execute the command: npm install mockjs-- save, and install mockjs into the project.
two。 Create a mock folder
Under the src directory, create a mock folder, and create an index.js under the mock folder
Index.js
Be careful! Get request needs to write url as regular, otherwise it cannot be intercepted.
Import Mock from 'mockjs'; / / introduce mockjsconst data = {Message:' query successful', Code: 1, Data: {Id:'', name:'}}; / / delay in intercepting requests / / Mock.setup ({/ / timeout: 3000 cycles /}); / / pay attention! ? Get request needs to write url as regular, otherwise Mock.mock cannot be intercepted (/ https:\ / www.baidu\ .com\ /, 'get', data); / / the parameter is the url to be intercepted (as long as the request address in the project is > included)
< 了这个参数,就会被拦截,第二个参数是请求方式,第三个参数是请求之后的response数据)export default Mock; .env.development: NODE_ENV='development'VUE_APP_URL = 'http://xxxx.xxx.xx.xxx:xxxx' VUE_APP_MOCK = true VUE_APP_MOCK = true 是为了在mainjs文件判断当前运行环境中是否要加入mockjs。 mainjs: 添加一行代码 process.env.VUE_APP_MOCK === 'true' && require('./mock/index'); // 如果process.env.VUE_APP_MOCK === 'true' 则引入mock文件夹下的index.js中的拦截.// 至于true为什么要加引号,大家体验一下不加的情况就能明白了,.env.development文件中的value都自动加了引号。不信的话试试下面这行展开// console.log(process.env.VUE_APP_MOCK, typeof process.env.VUE_APP_MOCK); 现在vue项目中就可以使用了: this.axios.get('https://www.baidu.com/').then(res =>{console.log (res.data) / / the returned result is data in mock- > index.js file); instructions for building mockjs in vue
In the development mode in which the front end is separated from the front end, the front end needs to request data from the back end (ajax request). However, in the actual development process, the front end and the back end will agree on an interface document, but the development progress of the front end is not consistent. When the back end does not improve the interface function, the front end needs to simulate the data return locally, and mockjs needs to be used in this case.
In other words, when the back-end interface is not developed, the front-end staff need to call the interface to test the front-end program, and the front-end staff can use mockjs to simulate the return data of the back-end interface.
With mockjs, we want to achieve our goal:
1. Be able to simulate the table record object data
2. It can simulate the operation of adding, deleting, modifying and querying interfaces.
3. Can be configured to intercept only manually configured interfaces
4. Only in the development environment can mockjs intercept
Install npm install mockjs-save-dev project build
New directory structure for src
Mock
Index.js is used to load mock's configuration for api interception
Mock-data.js is used to define mock mock data object methods
Api
UserApi.js mock Analog api Interface method definition File
Note: mockjs is generally only used for unit testing in a development environment
Mock/index.js configures files intercepted by mock to api
Code:
/ / introduce mockjsimport Mock from 'mockjs'// to mock simulation interface method file import userApi from'. / api/userApi.js'//import customerApi from'. / api/customerApi.js'// set 200-1000 Ms delay request data Mock.setup ({timeout: '200-1000'}) / * configure the api to be intercepted (using regular path matching) and api correspondence Mock simulation interface method of * / user Mock.mock (/\ / api\ / user\ / list/) 'get', userApi.getUserList) Mock.mock (/\ / user\ / info/,' get', userApi.getUser) Mock.mock (/\ / user\ / add/, 'post', userApi.createUser) Mock.mock (/ / user\ / del/,' post', userApi.deleteUser)
Mock/mock-data.js defines mock data object simulation method
Code example:
Import Mock from 'mockjs'const Random = Mock.Randomexport default {/ / cache mock data store: {}, / / get table mock data getTable: function (tableName) {if (this.store [tableName]) {return this.store [tableName]} else {let func = this [tableName]; this.store [tableName] = func () Return this.store [tableName]}, / / user table ifs_ua_account: function () {let List = [] const count = 200 for (let I = 0; I
< count; i++) { List.push( Mock.mock({ uid: i + 1, user_name: Random.name(), // 随机的英文姓名 real_name: Random.cname(), // 随机的中文姓名 "sex|1": ["男", "女"], // 随机取数组中一个元素 birthday: Random.date(), // 随机日期 mobile: /^1[3456789]\d{9}$/, // 手机号码 post: Random.pick(["设计", "开发", "测试", "实施"], 1, 3), // 从数组中随机取1-3个元素重新组成数组 address: '@county(true)', // 地址 email: "@email", // Email weight: Random.float(40, 90, 1, 1), // Random.float(整数位最小值, 整数位最大值, 小数位最小位数, 小数位最大位数) 实型 age: Random.integer(20, 55), // 随机取20 - 55之间的整数 e_memo: "@paragraph(1,2)", // 英文文本(句子) memo: "@cparagraph(1,2)", // 中文文本(句子)一个参数时,参1:句子的个数;两个参数时,参1:句子的最小个数 参2:句子的最大个数 "status|1": [0, 1, 2], // 随机取数组中一个元素 header: Random.image('200x100', '#50B347', '#FFF', 'Mock.js'), // 根据字符串text生成一张图片 Random.image( size, background, foreground, text ) }) ) } return List; }, // 角色表 ifs_ua_account_group: function(){ let List = [] const count = 8 const name = ["管理员", "项目经理", "测试经理", "开发经理"]; for (let i = 0; i < name.length; i++) { List.push( Mock.mock({ id: i + 1, role_name: name[i], role_memo: "@cparagraph(1,2)", role_code: /UG-\d{2}-\d{2}-\d{2}/ // "UG-NN-NN-NN"格式 }) ) } return List; }} mock/api/xxxxApi.js mock模拟api接口方法定义 示例代码: import Mock from 'mockjs'import mockdb from "@/mock/mock-data.js"// get请求从config.url获取参数,post从config.body中获取参数function param2Obj(url) { const search = url.split('?')[1] if (!search) { return {} } return JSON.parse( '{"' + decodeURIComponent(search) .replace(/"/g, '\\"') .replace(/&/g, '","') .replace(/=/g, '":"') + '"}' )}const Random = Mock.Random// 随机生成的用户列表数据let List = mockdb.getTable("ifs_ua_account")export default { /** * 获取列表 * 要带参数 * @param * @return {{code: number, message: string, data: *[]}} */ getUserList: config =>{const {name, page = 1, limit = 20} = param2Obj (config.url) return {code: 200, message:', data: List}}, / * add users * @ param name, addr, age, birth Sex * @ return {{code: number, data: {message: string}} * / createUser: config = > {const {name, addr, age, birth Sex} = JSON.parse (config.body) console.log (JSON.parse (config.body)) List.unshift ({id: Mock.Random.guid (), name: name, addr: addr, age: age, birth: birth Sex: sex}) return {code: 20000, data: {message: 'added successfully'} / * Delete user * @ param id * @ return {*} * / deleteUser: config = > {const {id} = param2Obj (config.url) if (! id) {return {code:-999 Message: 'incorrect parameters'} else {List = List.filter (u = > u.id! = = id) return {code: 200, message: 'deleted successfully'}} project configuration
Mockjs intercepts requests in dev environment
In the .env.development development environment variable configuration file, add variables
VUE_APP_MOCK = 1
Add the following code to the main.js file
/ / mock configuration to load mockjsprocess.env.VUE_APP_MOCK & & require ('@ / mock/index.js') project testing only in dev environment
The previous project has been built and configured, and now you can call axios to access api for testing
Let's first create a new userApi.js file in the src/api/ directory to define the method to request from the backend
Src/api/userApi.js Code:
Import https from'@ / https.js'const userApi = {baseUrl:'/ api', getUserList: function (params) {return https.fetchGet (this.baseUrl + "/ user/list", {});},}; export default userApi
Then, in App.vue, we introduce src/api/userApi.js, call the getUserList () method, the console prints out the returned data, and the test is complete.
UserApi.getUserList () .then ((response) = > {console.log (response.data)}) development process
First of all, we know that mock is used to simulate the return of the interface, so we need to define the interface input parameters and return confirmation.
Also, we need to define the api method in the src/api/ directory
These are two prerequisites.
Then, there is the front-end test. When we find that the back-end interface has not been developed, we do the mock test ourselves.
So the process should be like this:
Definition of interface input parameters and return
Complete the front-end function development
Mock/mock-data.js adds the interface to return the data model (this step is optional. It is not clear whether to put the data model definition here separately or directly into the xxxApi.js. In the actual project application, it will be confirmed according to the situation.)
Mock/api/xxxApi.js add api interface mock method
Mock/index.js add api route intercept configuration
This is the end of the article on "how to configure mockjs in vue cli4 in dev environment and build environment". Thank you for reading! I believe you all have a certain understanding of "how to configure mockjs in vue cli4 in dev environment and build environment". If you want to learn more, you are welcome to follow the industry information channel.
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.