1. 程式人生 > >新版vue獲取本地json文件數據

新版vue獲取本地json文件數據

caption class assets ngs r.js rewrite TBase aac htm

現在升級後的vue沒有dev-server.js和dev-client.js,可以通過以下方式模擬後臺數據:

1.找到webpack.dev.conf.js這個文件,在const portfinder = require(‘portfinder‘)後面添加以下代碼:

 1 const express = require(‘express‘)
 2 const app = express()//請求server
 3 var appData = require(‘../data.json‘)//加載本地數據文件
 4 var seller = appData.seller//獲取對應的本地數據
5 var goods = appData.goods 6 var ratings = appData.ratings 7 var apiRoutes = express.Router() 8 app.use(‘/api‘, apiRoutes)//通過路由請求數據 9 10 devServer: { 11 clientLogLevel: ‘warning‘, 12 historyApiFallback: { 13 rewrites: [ 14 { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, ‘index.html‘) },
15 ], 16 }, 17 hot: true, 18 contentBase: false, // since we use CopyWebpackPlugin. 19 compress: true, 20 host: HOST || config.dev.host, 21 port: PORT || config.dev.port, 22 open: config.dev.autoOpenBrowser, 23 overlay: config.dev.errorOverlay 24 ? { warnings: false
, errors: true } 25 : false, 26 publicPath: config.dev.assetsPublicPath, 27 proxy: config.dev.proxyTable, 28 quiet: true, // necessary for FriendlyErrorsPlugin 29 watchOptions: { 30 poll: config.dev.poll, 31 }, 32 //以下是添加的代碼: 33 before(app) { 34 app.get(‘/api/seller‘, (req, res) => { 35 res.json({ 36 errno: 0, 37 data: seller 38 })//接口返回json數據,上面配置的數據seller就賦值給data請求後調用 39 }), 40 app.get(‘/api/goods‘, (req, res) => { 41 res.json({ 42 errno: 0, 43 data: goods 44 }) 45 }), 46 app.get(‘/api/ratings‘, (req, res) => { 47 res.json({ 48 errno: 0, 49 data: ratings 50 }) 51 }) 52 } 53 54 55 },

技術分享圖片

2.運行npm run dev重啟項目(註意,不重啟,項目是不起效的):

技術分享圖片技術分享圖片?

3.在地址欄測試(以下就是獲取到data.json裏的數據):

技術分享圖片技術分享圖片?

技術分享圖片技術分享圖片?

技術分享圖片技術分享圖片?

新版vue獲取本地json文件數據