
在项目开发的过程中,如果后台接口还未开发完成,这个时候所以我们可以自建一个假数据文件(如data.json)到项目文件夹中,这样我们就可以模仿后台的数据进行开发。但是,如何在一个vue.js 项目中引入本地的json文件呢,下面就将步骤贴出来。
整个项目是由vue-cli脚手架搭建而成。具体项目结构如下:
1:首先我们使用vue-cli脚手架工具打包成上图所示的样子,不会vue-cli请跳转至这里:传送门
2:我们找到bulid>dev-server.js,然后打开
3:在里面加入这段代码,大概在20行左右)。
var app = express() // 从这后面开始加 var goodsData = require('../data.json')
var router = express.Router()
router.get("/goods", function (req,res) {
res.json(goodsData)
})
app.use(router)
这里用到的是node.js+express框架的知识。
4:将json文件放入项目中
{
"status":"0",
"result":[
{
"productId":"10001",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"mi6.jpg"
},
{
"productId":"10002",
"productName":"小米笔记本",
"prodcutPrice":"3999",
"prodcutImg":"note.jpg"
},
{
"productId":"10003",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"mi6.jpg"
},
{
"productId":"10004",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"1.jpg"
},
{
"productId":"10001",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"mi6.jpg"
},
{
"productId":"10002",
"productName":"小米笔记本",
"prodcutPrice":"3999",
"prodcutImg":"note.jpg"
},
{
"productId":"10003",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"mi6.jpg"
},
{
"productId":"10004",
"productName":"小米6",
"prodcutPrice":"2499",
"prodcutImg":"1.jpg"
}
] }
5: 在某个组件中使用axios或者vue-resource调用:
<script>
import axios from 'axios'
export default{
data(){
return { }
}
mounted () {
this.getGoodsList()
},
methods: {
getGoodsList () {
axios.get('/goods').then((res) => {
var result = res.data
console.log(result)
})
}
}
}
</script>
6:页面中打印这个结果: