自定义插件+自定义fetch插件

  1. 在src下创建plugins/fetch.js

  2. fetch.js中内容:

    let baseUrl;
    
    export async function $fetch (url, options) {
      // credentials: 'include' 解决跨域问题
      const finalOptions = Object.assign({}, {
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
      }, options)
      const response = await fetch(`${baseUrl}${url}`, finalOptions);
      if (response.ok) {
        const data = await response.json();
        return data;
      } else {
        const message = await response.text();
        const error = new Error(message);
        error.response = response;
        throw error
      }
    }
    
    export default {
      install(Vue, options) {
        // console.log('Installed!', options);
    
        baseUrl = options.baseUrl;
        Vue.prototype.$fetch = $fetch;
      }
    }
    
  3. 在main.js中注册插件:

    // 全局配置
    import VueFetch, { $fetch } from './plugins/fetch';
    
    Vue.use(VueFetch, {
      baseUrl: '/api'
    });
    
  4. 如何使用:

    // 用法1
    async login() {
      this.$state.user = await this.$fetch('/login', {
        method: 'POST',
        body: JSON.stringify({
          username: this.username,
          password: this.password,
        }),
      });
      this.$router.replace(this.$route.params.wantedRoute || { name: 'home' })
    },
    // 用法2 
    async created() {
      this.loading = true;
      try {
        this.ticket = await this.$fetch(`/ticket/${this.id}`);
      }catch (e) {
        this.error = e;
      }
      this.loading = false;
    },
    
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容