您的位置:首页 > 产品设计 > UI/UE

vue开发中,对本地数据地址进行请求

2018-03-30 19:58 656 查看

原版配置在dev-server.js中,而新版的vue-webpack-template删除了dev-server.js,用webpack.dev.conf.js代替了,所以需要在webpack.dev.conf.js中进行配置。

先将data.json文件放入项目中

例如:data.json文件格式为

{
    "result" : {
        "xxx" : "xxx",
        "xxx" : "xxx"
   }
}

webpack.dev.conf.js目录中

const express = require('express')  //导入express模块
const app = express()  //创建一个express应用
const appData = require('../data.json')  //导入json文件
const goods = appData.result  //数据内容保存到goods中
const apiRoutes = express.Router()  //创建一个路由
app.use('/api', apiRoutes)  //将请求地址发送到路由
在devServer: {}中
before(app){
    app.get('/api/goods', (req,res) => {
        res.json({
            erron: 0,
            data: goods
        })
    })


启动服务,在地址栏输入localhost:8080/api/goods可以看到数据已经获取到

在vue中,使用vue-resource请求数据
在main.js中

import vueResource from 'vue-resource'  //导入vue-resource
Vue.use(vueResource)  //引用vueResource
在App.vue中
created() {
    this.$http.get('/api/goods').then((response) => {
        response = response.body
        console.log(response)
    })
}
在控制台可以看到数据已经请求到了

可以定义一个空对象,将请求到的数据保存起来
export default {
    data() {
        return {
            goods: {}
        }
    },
    created() {
    this.$http.get('/api/goods').then((response) => {
        response = response.body
        this.goods = response.data
        })
    }
}
这样数据就保存到goods中了
在组件中传人goods
在组件中用props接收
props: {
    goods: {
        type: Object
    }
}
之后就可以绑定数据了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐