詳解vue-cli中模擬數(shù)據(jù)的兩種方法
在main.js中引入vue-resource模塊,Vue.use(vueResource).
1.使用json-server(不能用post請求)
接下來找到build目錄下的webpack.dev.conf.js文件,在const portfinder = require('portfinder')后面引入json-server.
/*引入json-server*/
const jsonServer = require('json-server')
/*搭建一個server*/
const apiServer = jsonServer.create()
/*將db.json關(guān)聯(lián)到server*/
const apiRouter = apiServer.router('db.json')
const middlewares = jsonServer.defaults()\
apiServer.use(apiRouter)
apiServer.use(middlewares)
/*監(jiān)聽端口*/
apiServer.listen(3000,(req,res)=>{
console.log('jSON Server is running')
})
現(xiàn)在重啟服務(wù)器后瀏覽器地址欄輸入localhost:3000能進(jìn)入如下頁面則說明json server啟動成功了
現(xiàn)在找到config文件夾下的index.js文件,在dev配置中找到proxyTable:{} 并在其中配置
'/api':{
changeOrigin:true, //示范允許跨域
target:"http://localhost:3000", //接口的域名
pathRewrite:{
'^/api':'' //后面使用重寫的新路徑,一般不做更改
}
}
現(xiàn)在可以使用localhost:8080/api/apiName 請求json數(shù)據(jù)了
在項(xiàng)目中通過resource插件進(jìn)行ajax請求
在data (){}前使用鉤子函數(shù)created:function(){
this.$http.get('/api/newsList')
.then(function(res){
this.newsList = res.data //賦值給data中的newsList
},function(err){
console.log(err)
})
}
2.使用express(可以使用post請求)
在項(xiàng)目中新建routes文件并在其中新建api.js,內(nèi)容如下:
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')
}
})
接下來找到build目錄下的webpack.dev.conf.js文件,在const portfinder = require('portfinder')后面引入express,如下:
const express = require('express')
const app = express()
const api = require('../routes/api.js')
app.use('/api',api)
app.listen(3000)
現(xiàn)在找到config文件夾下的index.js文件,在dev配置中找到proxyTable:{} 并在其中配置
'/api':{
changeOrigin:true, //示范允許跨域
target:"http://localhost:3000", //接口的域名
pathRewrite:{
'^/api':'/api' //后面使用重寫的新路徑,一般不做更改
}
}
重啟之后,便可以post請求訪問數(shù)據(jù)了.
總結(jié)
以上所述是小編給大家介紹的vue-cli中模擬數(shù)據(jù)的兩種方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue父子組建的簡單通信之控制開關(guān)Switch的實(shí)現(xiàn)
這篇文章主要介紹了Vue父子組建的簡單通信之控制開關(guān)Switch的實(shí)現(xiàn),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06
vue-resource post數(shù)據(jù)時碰到Django csrf問題的解決
這篇文章主要介紹了vue-resource post數(shù)據(jù)時碰到Django csrf問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
vue使用canvas實(shí)現(xiàn)移動端手寫簽名
這篇文章主要為大家詳細(xì)介紹了基于vue使用canvas實(shí)現(xiàn)移動端手寫簽名,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-09-09
Mint UI實(shí)現(xiàn)A-Z字母排序的城市選擇列表
這篇文章主要為大家詳細(xì)介紹了Mint UI實(shí)現(xiàn)A-Z字母排序的城市選擇列表,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
詳解VScode編輯器vue環(huán)境搭建所遇問題解決方案
這篇文章主要介紹了VScode編輯器vue環(huán)境搭建所遇問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

