vue高仿饿了么学习笔记(四)—— Vue Resource

一、Vue Resource

1)安装 Vue Resource

github:https://github.com/pagekit/vue-resource

查看github上关于 Vue Resource 的安装方式,选择 yarn 或者 npm 安装。

2)注入 Vue Resource

import Vue from 'vue';
import VueResource from 'vue-resource'; // 新增
import App from './App';
import router from './router';

Vue.use(VueResource); // 新增

Vue.config.productionTip = false;

... // 省略部分已有内容

3)mock 数据

在 build/webpack.dev.conf.js 中 mock 服务

... // 省略部分已有内容
const portfinder = require('portfinder')

// 添加 mock 数据 新增
const express = require('express') // 需 npm 安装 express
const app = express()
var appData = require('../data.json') // 该文件保存了所有的数据 放在根目录中
var goods = appData.goods
var seller = appData.seller
var ratings = appData.ratings
var apiRoutes = express.Router()
app.use('/api', apiRoutes)

const HOST = process.env.HOST
... // 省略部分已有内容

注:data.json 的内容参考 https://github.com/lwl0812/vue-sell 中的 data.json 文件

在 webpack.dev.conf.js 中找到 devServer,添加如下代码:

devServer: {
   // ... 省略部分已有内容
    watchOptions: {
      poll: config.dev.poll,
    },
   // 以下为新增的接口
    before(app) {
      app.get('/api/appData', (req, res) => {
        res.json({
          errno: 0,
          data: appData
        })
      }),
      app.get('/api/goods', (req, res) => {
        res.json({
          errno: 0,
          data: goods
        })
      }),
      app.get('/api/ratings', (req, res) => {
        res.json({
          errno: 0,
          data: ratings
        })
      }),
      app.get('/api/seller', (req, res) => {
        res.json({
          errno: 0,
          data: seller
        })
      })
    }
  },

重启服务,然后在浏览器窗口打开 localhost:8082/api/appData,可看到数据请求成功。

4)使用 Vue Resource

参考官网的使用方式

在 App.vue 中

import header from './components/header/header';

  const ERR_OK = 0; // 新增

  export default {
    data() {
      return {
        seller: {}
      };
    },
    created() { // 新增
      this.$http.get('/api/goods').then((response) => {
        const res = response.body;
        if (res.errno === ERR_OK) {
          this.goods = res.data; // 获取 goods
        }
      });
      this.$http.get('/api/ratings').then((response) => {
        const res = response.body;
        if (res.errno === ERR_OK) {
          this.ratings = res.data; // 获取 ratings
        }
      });
      this.$http.get('/api/seller').then((response) => {
        const res = response.body;
        if (res.errno === ERR_OK) {
          this.seller = res.data; // 获取 seller
        }
      });
    },
    components: {
      'v-header': header
    }
  };

 

posted @ 2018-08-26 21:52  狸子同学  阅读(538)  评论(0编辑  收藏  举报