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 @   狸子同学  阅读(540)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 赶AI大潮:在VSCode中使用DeepSeek及近百种模型的极简方法
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地
点击右上角即可分享
微信分享提示