vue 全家桶概括下来就是
项目构建工具 (vue-cli)
路由 (vue-router)
状态管理 (vuex)
http 请求工具
vue 有自己的 http 请求工具插件 vue-resource, 但是 vue2.0 后作者就不在更新了, 后更推荐 axios.
下面是 vue 项目中 axios 常用的方法, 以及生成虚拟数据的 easy-mock 的使用方法.
一, axios 安装和 easy-mock 的使用
1. axios
axios 基于 http 客户端的 promise, 面向浏览器和 Node.JS. 参考地址: https://www.kancloud.cn/yunye/axios/234845
特点
浏览器端发起 XMLHttpRequests 请求
node 端发起 http 请求
支持 Promise API
监听请求和返回
转化请求和返回
取消请求
自动转化 JSON 数据
客户端支持抵御
安装
NPM install --save axios
为了解决 post 默认使用的是 x-www-from-urlencoded 去请求数据, 导致请求参数无法传递到后台, 所以还需要安装一个插件 QS
- NPM install qs
- 2. easy-mock
Easy Mock 是一个可视化, 并且能快速生成 模拟数据 的持久化服务. 不需要再本地安装, 只需要到官网上注册登陆后加入或新建项目, 在项目内定义接口和返回数据的格式.
地址: https://www.easy-mock.com/login
步骤如下:
1) 登陆
2) 新建项目
3) 新建接口, Base URL 是访问地址
4) 定义接口名称和数据返回格式
这样一个接口就定义好了, 我们可以通过请求工具访问, 就可以得到 /login 中刚定义的数据. 更多定义 easy-mock 返回数据格式的方式, 具体请参考官网例子.
二, axios 使用
axios 的实例方法和配置很多, 下面只是常用基本的封装和使用方式.
在 vue 项目中 src 文件夹下, 有这几个需要新增的地方.
1. appCount.JS 文件
- const HTTP_BASE_URL = 'https://www.easy-mock.com/mock/5d5f5a3f6778c215243b94ea/' // easy-mock
- const TOKEN = '1234' // token
- export default {
- HTTP_BASE_URL,
- TOKEN
- }
在 appCount.JS 文件中, 我们可以放一些全局的变量. 例如: 访问地址的 ip,token 常量, 超时取消请求的时常等.
2. request.JS 文件
- import axios from 'axios'
- import appCONST from './appCount.js'
- const requestData = async (url, params = {}) => {
- let res = await axios({
- url: appCONST.HTTP_BASE_URL + url,
- data: params || {},
- method: params.method || 'POST',
- header: params.header || {
- 'content-type': 'application/json'
- }
- })
- console.log(res)
- if(requestSuccess(res)) {
- return res.data
- } else {
- throw requestException(res)
- }
- }
- /**
- * 请求成功
- */
- function requestSuccess(res) {
- const status = res.status
- // 请求错误
- if (status !== 200) {
- return false
- }
- const resData = res.data
- return !(resData && resData.code !== 1)
- }
- /**
- * 异常
- */
- function requestException(res) {
- const error = {}
- error.serverCode = res.status
- const resData = res.data
- error.code = resData.code
- error.msg = resData.msg || '系统错误'
- error.data = resData.result || {}
- return error
- }
- // 导出封装函数
- export default {
- requestData
- }
在上面文件中, requestData 方法是我们封装的 axios 请求, 在方法中, 我并没有使用到安装时 qs. 因为在方法中定义了请求头 content-type 的类型是 JSON 格式, 所以参数格式直接传对象进来就可以了.
如果没有定义 content-type 的类型, 那么默认是 application/x-www-form-urlencoded. 请求参数在 Form Data 中, 只能上传键值对, 并且键值对都是间隔分开的.
参数形式: name1=value1&name2=value2. 那么最好引入 qs, 然后将 params 格式化一下, data:qs.stringify(params).
3. util.JS
可以写一些公共的方法, 例如: 存取本地缓存, 参数格式化等方法. 然后在需要用到的地方导入这个文件, 就可以使用其中的方法了.
- export const localSave = (key, value) => {
- localStorage.setItem(key, value)
- }
- export const localRead = (key) => {
- return localStorage.getItem(key) || ''
- }
使用方式
- <script>
- import * as util from '@/libs/util'
- export default {
- name: 'login',
- data() {
- return {
- da:''
- }
- },
- methods: {
- submit() {
- util.localSave('data', '123')
- }
- }
- }
- </script>
4. API.JS
- import wxRequest from '../libs/request'
- // 用户登录
- const login = (params) => wxRequest.requestData('login', params)
- export default {
- login
- }
5. 调用接口
- <template>
- <div>
- <button @click="submit()"> 点我登陆 </button>
- </div>
- </template>
- <script>
- import API from '@/api/api'
- export default {
- name: 'login',
- data() {
- return {
- da:''
- }
- },
- methods: {
- async submit() {
- try {
- const dd = await API.login()
- console.log(dd)
- } catch(err) {
- console.log(err)
- }
- }
- }
- }
- </script>
更多方法, 例如添加拦截器也挺好用.
来源: http://www.bubuko.com/infodetail-3170628.html