阅读 95

Vue+TS中全局绑定axios、storage、接口地址的方法

全局绑定axios(在TypeScript中)

  1. 通过cnpm安装到项目中。

cnpm i axios --save 复制代码

  1. 在main.ts中引入下面的接口和组件

import Axios,{AxiosInstance} from  'axios' 复制代码

  1. 在main.ts中进行如下声明

declare module '@vue/runtime-core' {   interface ComponentCustomProperties {     $axios: AxiosInstance   } } 复制代码

  1. 在方法中可以直接通过this.$axios进行调用。

requestData() {   this.$axios.get('https://s.itying.com/api/v1/login').then(res => {     console.log(res);   }) } 复制代码

封装并全局绑定storage

封装storage

  1. 首先创建一个storage.ts文件

  2. 下面是storage.ts文件中的内容

export interface StorageInstance {   set(key: string,value: any): void;   get(key: string): any;   remove(key: string): void; } class StorageClass implements StorageInstance {   set(key: string, value: any): void {     localStorage.setItem(key,JSON.stringify(value));   }   get(key: string): any {     let temp = localStorage.getItem(key);     if (temp) {       return JSON.parse(temp);     }     return null;   }   remove(key: string): void {     localStorage.removeItem(key);   } } let Storge = new StorageClass(); export default Storage; 复制代码

全局绑定storage

需要注意的是,我们全局绑定的是我们上一步暴露的storage。

  1. 引入已经封装好的storage。

import Storage,{StorageInstance} from './model/storage' 复制代码

  1. 声明module

declare module '@vue/runtime-core' {   interface ComponentCustomProperties {     $axios: AxiosInstance,     $storage: StorageInstance   } } 复制代码

  1. 挂载到全局

app.config.globalProperties.$storage = Storage 复制代码

  1. 通过this.$storage即可访问

this.$storage.set("token",res.data.token) 复制代码

封装接口地址

  1. 创建config.ts

  2. 在文件中暴露相关接口地址

export interface ConfigInstance {   apiUrl: string;   imgUrl: string; } class ConfigClass implements ConfigInstance {   apiUrl: string;   imgUrl: string;   constructor() {     this.apiUrl = 'https://s.itying.com/api/v1';     this.imgUrl = 'https://s.itying.com'   } } const Config = new ConfigClass(); export default Config; 复制代码

  1. 在main.ts中进行声明与挂载

import Config,{ConfigInstance} from './model/config' declare module '@vue/runtime-core' {   interface ComponentCustomProperties {     $axios: AxiosInstance,     $storage: StorageInstance,     $config: ConfigInstance   } } app.config.globalProperties.$config = Config 复制代码

  1. 组件中获取只需通过this.$config.apiUrl即可。

总结

在vue中进行全局绑定是一个非常重要和常用的操作,以api请求地址为例,假如一个大型的vue项目每一个接口地址都是写死的,那么一旦api地址发生更改,这将给修改带来极大的困难,但是如果我们绑定到全局,修改起来就是十分简单的一件事情了,所以将一些常用属性和方法绑定到全局中是非常重要的。


作者:Always_positive
链接:https://juejin.cn/post/7056329523398180894


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐