首页 > 其他 > 详细

vue2.0模拟后台数据交互

时间:2019-11-19 17:48:15      阅读:76      评论:0      收藏:0      [点我收藏+]

一、模拟后台数据,需要vue-resource组件

  1.$npm install vue-resource --save

  2.在main.js中引入并使用

import VResource from ‘vue-resource‘

Vue.use(VResource);

二、模拟后台数据配置

  这里用express方法,可以支持post和get请求,更实用

  1.找到webpack.dev.conf.js文件,在头部引入express

var express = require(‘express‘)

  然后拉伸至底部,插入如下代码:

//express 配置server
var apiServer = express()
var bodyParser = require(‘body-parser‘)
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require(‘fs‘)
apiRouter.route(‘/:apiName‘) //接口路径
  .all(function (req, res) {
    fs.readFile(‘./data.json‘, ‘utf8‘, function (err, data) {  //读取接口文件
      if (err) throw err
      var data = JSON.parse(data)
      if (data[req.params.apiName]) {
        res.json(data[req.params.apiName])
      }
      else {
        res.send(‘no such api name‘)
      }

    })
  })

apiServer.use(‘/api‘, apiRouter);
apiServer.listen(3000, function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log(‘Listening at http://localhost:‘ + 3000 + ‘\n‘)
})

  2.端口号的跨域问题,做好接口的代理配置:找到config/index.js,插入代码

//配置转化:从3000 => 8080
    //这下面就是要加的代码!!!!!
    proxyTable:{
      ‘/api‘:‘http://localhost:3000/‘
    },

  完整代码如下:

// Various Dev Server settings
    host: ‘localhost‘, // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    //配置转化:从3000 => 8080
    //这下面就是要加的代码!!!!!
    proxyTable:{
      ‘/api‘:‘http://localhost:3000/‘
    },

  3.模拟后台数据:在根目录下新建文件data.json

{
  "newsList": [
    {
      "title": "数据统计",
      "url": "http://starcraft.com"
    },
    {
      "title": "数据预测",
      "url": "http://warcraft.com"
    },
    {
      "title": "流量分析",
      "url": "http://overwatch.com"
    },
    {
      "title": "广告发布",
      "url": "http://hearstone.com"
    }
  ]
}

  4.在vue文件中请求数据:

export default {
    data(){
      return{
        newsList: []
      }
    },
    mounted(){
      this.getDatas();
    },
    methods:{
      getDatas(){
        let _this = this;
        this.$http.get(‘api/newsList‘).then((res)=>{
          _this.newsList = res.data;
        }).catch((err)=>{

        })
      }
    }
  }

 

vue2.0模拟后台数据交互

原文:https://www.cnblogs.com/ddzhou/p/11890708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!