在build文件夾下找到webpack.dev.conf.js文件,在const portfinder = require('portfinder')後添加
const express = require('express')
const app = express()
const appData = require('../data.json') // 加載本地json文件
const seller = appData.seller // 獲取對應本地數據
const goods = appData.goods
const ratings = appData.ratings
const apiRoutes = express.Router()
app.use('/api',apiRoutes)
然後找到devServer,插入以下代碼:
//然後找到devSeerver,在裏面添加
before (app) {
app.get('/api/seller',(reg,res) => {
res.json({
errno: 0,
data: seller
}) // 接口返回json數據,上面配置的數據seller就複製給data請求後調用
}),
app.get('/api/goods',(reg,res) => {
res.json({
errno: 0,
data: goods
}) // 接口返回json數據,上面配置的數據goods就複製給data請求後調用
}),
app.get('/api/ratings',(reg,res) => {
res.json({
errno: 0,
data: ratings
}) // 接口返回json數據,上面配置的數據ratings就複製給data請求後調用
})
}
請求訪問
<script>
import header from './components/header/header.vue'
const ERR_OK = 0
export default {
data () {
return {
seller: {}
}
},
created () {
this.$http.get('/api/seller').then((response) => {
response = response.body; // 獲取到數據
if (response.errno === ERR_OK) {
this.seller = response.data;
console.log(this.seller);
}
})
},
components: {
'v-header': header
}
}
</script>
最後重新啓動項目即可訪問npm run dev
上面是vue-cli2.0的模式,在vue-cli3.0搭建項目的時候,目錄結構發生了變化,沒有了bulid-webpack.dev.conf.js文件;
所以配置有些稍微變動,
首先在根目錄創建vue.config.js文件,內容爲:
const express = require('express') // 引入express框架
const app = express() // 實例化對象
const appData = require('./data.json') // 引入數據
const option = appData.option // 取出數據
const apiRoutes = express.Router() // 引入路由
app.use('/api', apiRoutes)
module.exports = {
baseUrl: '/', // 基本路徑
outputDir: 'dist', // 輸出文件目錄
productionSourceMap: true, // 生產環境是否生成sourceMap文件
devServer: {
// port: 9090, // 端口號
// open: true, // 啓動完自動打開瀏覽器
before(app) {
app.get('/api/option', (req, res) => {
res.json({
code: 0,
data: option
})
})
}
}
}
然後將json文件放到與這個配置文件放到同級目錄下;
使用方式還跟之前差不多
this.$axios.get('/api/option').then((response) => {
response = response.data
if (response.code == 0) {
console.log(response.data)
this.option = response.data[0] // 獲取到數據
}
})
}