一、前言
vue-cli(版本更新)妙啃,由原來的
2.8.1
升級為2.9.1
档泽。主要改變是原來在build
文件夾下的dev-server.js
刪掉了,增加了webpack.dev.conf.js
揖赴。導致原來通過express
方式引入的數(shù)據(jù)找不到馆匿。本文將針對此問題,提供兩種結局方案燥滑。
二渐北、方案A— 使用node中的express
我們知道在2.9.1
的版本中沒有express
。
-
注意: 這里安裝
vue-resource
后需要在main.js
注冊并使用下
import VueResource from 'vue-resource'
Vue.use(VueResource)
- 在
webpack.dev.conf
配置express并設置路由規(guī)則
'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const baseWebpackConfig = require('./webpack.base.conf')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')
/* datura_lj 增加express 20171126 */
const express = require('express')
const app = express()
var appData = require('../goods.json')//加載本地數(shù)據(jù)文件
var goods = appData.goods
var apiRoutes = express.Router()
app.use('/api', apiRoutes)
/* 增加express end */
const devWebpackConfig = merge(baseWebpackConfig, {
module: {
rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
},
// cheap-module-eval-source-map is faster for development
devtool: config.dev.devtool,
// these devServer options should be customized in /config/index.js
devServer: {
clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
compress: true,
host: process.env.HOST || config.dev.host,
port: process.env.PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay ? {
warnings: false,
errors: true,
} : false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
/* datura_lj 增加express 20171126 */
before(app) {
app.get('/api/goods', (req, res) => {
res.json({
code: 0,
data: goods
})
})
}
/* datura_lj 增加路由規(guī)則 end */
},
plugins: [
new webpack.DefinePlugin({
'process.env': require('../config/dev.env')
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
new webpack.NoEmitOnErrorsPlugin(),
// https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'index.html',
inject: true
}),
]
})
module.exports = new Promise((resolve, reject) => {
portfinder.basePort = process.env.PORT || config.dev.port
portfinder.getPort((err, port) => {
if (err) {
reject(err)
} else {
// publish the new Port, necessary for e2e tests
process.env.PORT = port
// add port to devServer config
devWebpackConfig.devServer.port = port
// Add FriendlyErrorsPlugin
devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
compilationSuccessInfo: {
messages: [`Your application is running here: http://${config.dev.host}:${port}`],
},
onErrors: config.dev.notifyOnErrors
? utils.createNotifierCallback()
: undefined
}))
resolve(devWebpackConfig)
}
})
})
-
檢測
npm run dev
后铭拧,在瀏覽器地址欄中輸入http://127.0.0.1:8080/api/goods
即可看到數(shù)據(jù) -
注意 新建
goods.json
引入時候的路徑
二赃蛛、方案B— 使用json-server,啟動一個server
-
新建
server
文件夾并配置相關信息
|--server
|--package.json
|--static
|--config.js
|--db.json
|--server.js
1. package.json
{
"name": "json-server-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"server": "cd static && nodemon server.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"json-server": "^0.9.6",
"nodemon": "^1.11.0"
}
}
2. config.js
module.exports = {
SERVER:"127.0.0.1",
PORT: 9527,
DB_FILE:"db.json"
};
3. db.json
數(shù)據(jù)文件
4. server.js
const path = require('path');
const config = require('./config');
const jsonServer = require('json-server');
const ip = config.SERVER;
const port = config.PORT;
const db_file = config.DB_FILE;
const server = jsonServer.create();
const router = jsonServer.router(path.join(__dirname, config.DB_FILE));
const middlewares = jsonServer.defaults();
server.use(jsonServer.bodyParser);
server.use(middlewares);
server.use((req, res, next) => {
res.header('X-Hello', 'datura_lj');
next();
})
router.render = (req, res) => {
res.jsonp({
code: 0,
body: res.locals.data
})
}
server.use("/api", router);
server.use(router);
server.listen({
host: ip,
port: port
}, function () {
console.log(JSON.stringify(jsonServer));
console.log(`JSON Server is running in http://${ip}:${port}`);
});
-
檢測 在
server
文件下執(zhí)行npm run server
后搀菩,在瀏覽器地址欄中輸入http://127.0.0.1:9527/goods
即可看到數(shù)據(jù)
三呕臂、在vue
組件中,調取數(shù)據(jù)
created () {
/*
* 方式一
* 使用node中的express
*/
/*this.$http.get('/api/goods').then((data) => {
if(data.body.code == 0){
this.imgArr = data.body.data;
console.log(this.imgArr)
}
})*/
/*
* 方式二
* 使用json-server方式
*/
this.$http.get('http://127.0.0.1:9527/goods').then((data) => {
console.log(data.body)
if(data.body.code == 0){
this.imgArr = data.body.body;
console.log(this.imgArr)
}
})
}
四肪跋、效果展示
五歧蒋、其他
本文只是針對數(shù)據(jù)問題解決,具體組件渲染以及路由規(guī)則州既,還請繼續(xù)看以前文章谜洽。
對以入門的朋友請看提高版本