且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在脚本中使用 Vue Router

更新时间:2023-12-05 21:28:46

这个问题适用于其他框架,如 React 和 Angular,应该类似解决.

This problem is is applicable to other frameworks like React and Angular and should be solved similarly there.

Router 实例在组件层次结构之外不可用,当 Axios 拦截器定义在模块范围内时无法访问它.

Router instance is unavailable outside component hierarchy, it cannot be accessed when Axios interceptor is defined in module scope.

修改全局 Axios 实例也是不明智的,因为它可以被第三方库使用,并且会给它们带来意想不到的副作用,这也使得测试中的清理变得更加复杂.

It's also unwise to modify global Axios instance because it can be used by third-party libraries and cause unexpected side effects for them, this also makes clean-up more complicated in tests.

本地 Axios 实例可以在 Vue 应用程序中定义,也允许定义特定选项,如基本 URL:

Local Axios instance can be defined in Vue application, also allows to define specific options like base URL:

Object.defineProperty(Vue.prototype, 'axios', {
  get() {
    return this.$root._axiosInstance;
  }
});

Vue.mixin({
  created() {
    if (this.$root === this) {
      let axiosInstance = axios.create({/*...*/});
      axiosInstance.interceptors.response.use(
        response => response,
        error => {
          ...
          this.$router.push(...);
          ...
        }
      );

      this._axiosInstance = axiosInstance;
    }
  }
});

并且在组件内部作为 this.axios 访问.

And is accessed as this.axios inside components.