This article mainly introduces two methods of simulating data in vue-cli. This article introduces you to you in very detail and has certain reference value. Friends in need can refer to it
Introduce vue-resource module into main.js, Vue.use(vueResource).
1. Use json-server (cannot use post request )
Next find thewebpack.dev.conf.js
file in the build directory and introduceafter
const portfinder = require('portfinder')json-server
.
/*引入json-server*/ const jsonServer = require('json-server') /*搭建一个server*/ const apiServer = jsonServer.create() /*将db.json关联到server*/ const apiRouter = apiServer.router('db.json') const middlewares = jsonServer.defaults()\ apiServer.use(apiRouter) apiServer.use(middlewares) /*监听端口*/ apiServer.listen(3000,(req,res)=>{ console.log('jSON Server is running') })
Now after restarting the server, enter localhost:3000 in the browser address bar to enter the following page, which means that the json server has been started successfully
Now find the index.js file in the config folder, find proxyTable:{} in the dev configuration and configure it in it
'/api':{ changeOrigin:true, //示范允许跨域 target:"http://localhost:3000", //接口的域名 pathRewrite:{ '^/api':'' //后面使用重写的新路径,一般不做更改 } }
Now you can uselocalhost:8080/api/apiName
to request json data
Passed in the project resource plug-in performs ajax request
Use hook function beforedata (){}
created:function(){
this.$http.get('/api/newsList') .then(function(res){ this.newsList = res.data //赋值给data中的newsList },function(err){ console.log(err) }) }
2. Use express (you can use post request)
Create a new routes file in the project and create a new api in it .js, the content is as follows:
const express = require('express') const router = express.Router() const apiData = require('../db.json') router.post('/:name',(req,res)=>{ if(apiData[req.params.name]){ res.json({ 'error':'0', data:apiData[req.params.name] }) }else{ res.send('no such a name') } })
Next, find thewebpack.dev.conf.js
file in the build directory, in ## After #const portfinder = require('portfinder')introduce express as follows:
const express = require('express') const app = express() const api = require('../routes/api.js') app.use('/api',api) app.listen(3000)
'/api':{ changeOrigin:true, //示范允许跨域 target:"http://localhost:3000", //接口的域名 pathRewrite:{ '^/api':'/api' //后面使用重写的新路径,一般不做更改 } }
How Vue-cli proxyTable solves cross-domain problems in the development environment
About vue.js before and after End-to-end data interaction operation of submitting data
The above is the detailed content of Two methods to analyze simulated data in vue-cli. For more information, please follow other related articles on the PHP Chinese website!