因项目需要需在登录页动态设置接口地址

页面

  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <el-form
      :model="form"
      :rules="rules"
      label-width="auto"
      ref="formRef"
      label-position="left"
    >
      <!--ip -->
      <el-form-item label="IP" prop="ip">
        <el-input v-model="form.ip" clearable maxlength="15">
          <template #prepend>
            <el-select v-model="form.select" style="width: 75px">
              <el-option label="http" value="http" />
              <el-option label="https" value="https" />
            </el-select>
          </template> </el-input
      ></el-form-item>
      <!-- 端口号 -->
      <el-form-item label="Port" prop="port">
        <el-input v-model="form.port" clearable maxlength="5" />
      </el-form-item>
    </el-form>
  </Layer>

接口IP存放在localStorage内

// 确定按钮
function submit() {
  formRef.value.validate((valid) => {
    if (valid) {
      localStorage.setItem("baseURL", JSON.stringify(form.value));
    }
  });
}

第一步新建 diffReq.js 用于存储之前的request.js axios配置信息 

import axios from "axios";
import store from "@/store";
import i18n from "../../locale/index";
import { ElMessage, ElMessageBox } from "element-plus";
export let isRelogin = { show: false };
function diffReq(baseURL) {
  const service = axios.create({
    baseURL: baseURL,
    timeout: 50000,
  });

  // 请求前的统一处理
  service.interceptors.request.use(
    (config) => {
      // JWT鉴权处理
      if (store.getters["user/SDKey"]) {
        config.headers["Authorization"] = store.state.user.SDKey;
      }
      return config;
    },
    (error) => {
      console.log(error); // for debug
      return Promise.reject(error);
    }
  );

  service.interceptors.response.use(
    
  return service;
}

// 错误处理
function showError(error) {

}

export default diffReq;

第二步在request.js中引入接口信息

import diffReq from "./diffReq.js";
function request({ method, url, data }) {
  let baseURL;
  const form = JSON.parse(localStorage.getItem("baseURL"));
  // // 缓存
  if (form) {
    baseURL = `${form.select}://${form.ip}:${form.port}`;
  } else {
    // 默认
    baseURL = "http://127.0.0.1:52888";
  }
  const request = diffReq(baseURL);
  return request({
    method,
    url,
    data,
  });
}
export default request;

接口文件数据不用动 

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐