vue模拟数据 | 您所在的位置:网站首页 › 用json做数据库 › vue模拟数据 |
json-server
建立模拟数据:在src同级目录下创建文件:db.json 首先先下载包 npm install json-server -g打开集成终端,设置端口,这个端口是你脚手架的端口号,方便代理 json-server db.json --port 8080打开package.json文件 然后在scripts中配置一个mock,这个端口号是访问你虚拟数据的端口号: "mock": "json-server db.json --port 3003" "scripts": { "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js", "start": "npm run dev", "build": "node build/build.js", "mock": "json-server db.json --port 3003"}, 执行 npm run dev![]() ![]() 发现 http://localhost:3003/ http://localhost:8080/是一样 6. 书写测试代码,你可以直接但APP.vue上测试,或者删掉重新配置,记得在main.js中y引入文件并直接渲染 render:(h) =>h(文件名) 这时候要才用多线程,也就是你要多开个终端,先关掉之前的终端,因为刚刚在json-server db.json --port 8080,8080端口被使用了,为了防止端口占用,全部关掉。然后重新一个启动json-server,一个启动项目npm run dev {{login}} export default { created: function () { this.$http.get('http://localhost:8080/login') .then((res) => { this.login = res.data }, (err) => { console.log(err) }) }, data () { return { login:[] } } } 代理服务器简单理解就是当你访问/api时你会映射到你的虚拟数据http://localhost:3003, 就是/api是http://localhost:3003的代言人!!!! 设置config/index.js 的proxyTable proxyTable: { '/api/': { target: 'http://localhost:3003', //将http://localhost:3003映射到/api changeOrigin: true, //是否跨域 pathRewrite: { '^/api': '', // 因为在 ajax 的 url 中加了前缀 '/api',而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 '/api' 转为 '/' } } },http://localhost:8080/api将会映射访问到http://localhost:3003页面,起到一个代理作用 修改请求的url地址 export default { created: function () { this.$http.get('/api/login') .then((res) => { this.login = res.data }, (err) => { console.log(err) }) }, data () { return { login:[] } } } 重新启动 npm run dev![]() ![]() 首先下包 npm install axios在main.js中引入 var axios = require('axios');发出请求 axios.get('/api/dataInData') .then(function(response){ console.log(response); }).catch(function(response){ console.log(response); });
|
CopyRight 2018-2019 实验室设备网 版权所有 |