ZeXu_
侠客
侠客
  • 最后登录2020-10-29
  • 发帖数12
阅读:5516回复:0

[Vue]# 前后端分离 3:前端 API.js

楼主#
更多 发布于:2020-07-16 11:36
# 前后端分离 3:前端 API.js  


> Author: ZeXu  


> Soft: WebStorm  
> 前期准备:
> 1. new Promise()
> 2. async 与 await


>
> 在 '前后端分离 2:传参'的前端部分中,我们在 main.js 中使用了一个 API
>
> 可是使用 API 的场景很多,虽然说在每一个需要用到的页面中都 引用一遍,连接一遍,当时写起来可能很快,对于 axios 的熟练度也会有明显增加,但是对于后续修改来说比较麻烦的
>
> 因此我们需要全局的文件来帮助我们做重复的事情,达到重复利用的目的,而且以后修改起来也很方便


# API.js


#### 创建


> src > js


我们先创建一个名为:api.js 的文件


    ``` javascript
        // # api.js
        
        import axios from 'axios'
        
        function API () {
            let get = (url, params) => {
                return new Promise((reslove, reject) => {
                    axios.get(url)
                        .then(response => {
                            reslove(response.data)
                        })
                        .catch(error => {
                            reject(error)
                        })
                })
            }.then(reslove => {
                return reslove
            }).catch(reject => {
                return reject
            })
            
            this.product = {
                getMethod () {
                    return get('/product')
                }
            }
        }
        
        export default new API ()
    ```  
> 这是一篇关于很厉害的关于 Promise 的文章
>
> [ES6---new Promise()讲解,Promise对象是用来干嘛的?应该怎么用?使用场景有哪些?](https://blog.csdn.net/hyupeng1006/article/details/80351174)
>


#### 使用


> 某组件.vue


    ``` javascript
        // # news.vue
        
        // # api.js 文件所在位置
        import API from '../../../js/api'
        
        // # 比如我们在 mounted () {} 中调用 api.js 中的 getMethod()
        mounted () {
            let get = API.product.getMethod()
            console.log('get:', get)
        }
    ```
前往控制台查看,得到的却是


    get:→ Promise {<pending>}
    > 点击箭头打开 get:Promise {<pending>}
    > 可以找到 后端返给我们的数据里面是有的  
    
这样的数据我们是不好使用的


> Promise的设计文档中说了,[[PromiseValue]]是个内部变量,外部无法得到,只能在then中获取  


那我们如何取到这些数据呢  


是的,异步与同步的问题,我们可以这样做:


    ``` javascript
        // # news.vue
        
        // # api.js 文件所在位置
        import API from '../../../js/api'
        
        // # 比如我们在 mounted () {} 中调用 api.js 中的 getMethod()
        async mounted () {
            let get = await API.product.getMethod()
            console.log('get:', get)
        }
    ```  
    
前往控制台,我们可以看到
    
    // # 控制台
    get:→{code: 0, data: {...}, message: '请求成功!'}  


#### 补充
> await-to-js


    $ npm install --save await-to-js
    
    ``` javascript
        // # api.js
        import axios from 'axios'
        import to from 'await-to-js'
        
        function API () {
            let get = (url, params) => {
                return to(new Promise((reslove, reject) => {
                    axios.get(url)
                        .then(response => {
                            reslove(response.data)
                        })
                        .catch(error => {
                            reject(error)
                        })
                }))
            }
            
            this.product = {
                getMethod () {
                    return get('/product')
                }
            }
        }
        
        export default new API ()
    ```
    
这个插件可以替换掉 new promise() 的 .then() 与 .catch()  


另外,


    ``` javascript
        async mounted () {
            // let get = await API.product.getMethod()
            // console.log('get:', get)
            
            // # 引入了 await-to-js 后 ,我们可以看到 get 是一个数组
            // # 我们可以将 get 替换成 [err, res]
            let [err, res] = await API.product.getMethod()
            console.log('err:', err)
            console.log('res:', res)
        }
    ```
游客


返回顶部

公众号

公众号