首页  >  问答  >  正文

javascript - vue-resource 如何二次封装

如何吧vue-resource 再次封装到一个js文件里面 如:

let Ajax = {
    Vue.http.get(url,data).then(
        // ...代码
        return data
    )
}

然后在别的地方直接调用 如:

save(){
    this.Ajax.get(url,data);
}
淡淡烟草味淡淡烟草味2663 天前1077

全部回复(2)我来回复

  • 大家讲道理

    大家讲道理2017-07-05 11:00:37

    // api.js
    
    export default {
        save (params = {}) {
          return Vue.http.get(url, { params }).then(res => {
            // some handling
            return res.data
          })
        },
        
        // ...
    }

    然后在其它文件中引入使用即可

    import api from './api'
    
    api.save({
      // params...
    }).then(data => {
      // ...
    })

    axios 吧,官方已不推荐使用 vue-resource 了,使用 axios 配合 vue-axios 使用

    回复
    0
  • 仅有的幸福

    仅有的幸福2017-07-05 11:00:37

    全局注册个插件

    https://vuefe.cn/v2/guide/plu...

    export default {
      install: function() {
        Vue.prototype.$ajax = Ajax;
      }
    }

    然后use该文件,接着就可以使用啦

    回复
    0
  • 取消回复