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 } };
文小白滴笔记~~
分类:
Vue 相关
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· PPT革命!DeepSeek+Kimi=N小时工作5分钟完成?
· What?废柴, 还在本地部署DeepSeek吗?Are you kidding?
· 赶AI大潮:在VSCode中使用DeepSeek及近百种模型的极简方法
· DeepSeek企业级部署实战指南:从服务器选型到Dify私有化落地