vue-cli的build的文件夹下没有dev-server.js文件,怎么配置本地数据
因为最新版本的vue-cli已经放弃dev-server.js,只需在webpack.dev.conf.js配置就行
新版webpack.dev.conf.js配置如下:
上面一张图是初始稿,只写引入本地数据那一条代码即可,
如下图:
需要安装express依赖
npm install express --save-dev
不需要安装express
在const portfinder = require(‘portfinder’)后添加
const express = require('express') // 不需要
const app = express() // 不需要
var appData = require('../src/goods.json') //加载本地数据文件
var router = express.Router() // 不需要
app.use('/api', router) // 不需要
//然后找到devServer,在里面添加
//接口返回json数据,下面配置的数据appData就赋值给data请求后调用
before(app) {
app.get('/api/appData', (req, res) => {
res.json({
error: 0,
data: appData
})
})
},
然后npm run dev,一定要重启 一下就可以http://localhost:8080/api/appData 访问了
http://localhost:8080
相关文件详细如下:
本地src目录下
goods.json
{
"error": 0,
"data": {
"status": "0",
"result": [
{
"productId": "10000",
"productName": "小米6",
"productPrice": "2499",
"productImg": "http://p0scbmmzr.bkt.clouddn.com/img/avatar0.jpg"
},
{
"productId": "10001",
"productName": "小米6",
"productPrice": "2499",
"productImg": "http://p0scbmmzr.bkt.clouddn.com/img/avatar1.jpg"
},
{
"productId": "10002",
"productName": "小米6",
"productPrice": "2499",
"productImg": "http://p0scbmmzr.bkt.clouddn.com/img/avatar2.jpg"
},
{
"productId": "10003",
"productName": "小米6",
"productPrice": "2499",
"productImg": "http://p0scbmmzr.bkt.clouddn.com/img/avatar3.jpg"
},
{
"productId": "10004",
"productName": "小米6",
"productPrice": "2499",
"productImg": "http://p0scbmmzr.bkt.clouddn.com/img/avatar4.jpg"
}
]
}
}
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
App.vue
<template>
<div id="app">
<HelloWorld/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
text-align: center;
}
</style>
HelloWorld.vue
<template>
<div class="hello">
<ul>
<li v-for="(item, key) in data">
<div class="box">
<img :src="item.productImg" alt="" class="figure">
<p>{{item.productId}}</p>
<p>{{item.productName}}</p>
<p>{{item.productPrice}}</p>
<hr/>
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
data: []
}
},
mounted () {
this.$axios.get('/api/appData').then(res => {
this.data = res.data.data.data.result;
console.log(res.data.data.data.result);
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.figure {
width: 100px;
height: 100px;
border-radius: 50px;
}
</style>