当前位置:网站首页 > Vue.js开发 > 正文

vue3中,axios的几种用法之抽离接口、post请求、get请求、.env.dev、网关标识、基准地址

vue3中,axios的几种用法之抽离接口、post请求、get请求、.env.dev、网关标识、基准地址

效果
在这里插入图片描述

1、直接使用
<div> <el-button type="primary" @click="handelDowload">下载预览</el-button> </div> <script lang="ts" setup> import axios from "axios"; import { downLoadxls } from "@/utils/utils.js"; // 下载预览 const handelDowload = () => { axios({ method: 'POST', url: process.env.VUE_APP_API_HOST + constant.ieopCollaborate + '/collaborate/directory/content/downloadPDF', data: { id: directoryId }, responseType: 'blob' }).then((res) => { if (res.data?.code) { ElMessage.error(res.data.message) } else { downLoadxls(res) setTimeout(function () { ElMessage.success("下载成功") }, 1000) } }) } </script> 

包含4个参数:

  • 请求方式method:POST
  • 请求地址url:url
  • 请求参数data:data
  • 定义类型responseType

引入的方法文件

src\utils\utils.js

//文件流导出数据处理 方式一 export function downLoadxls(res, fileName) { 
    let name; if (fileName) { 
    name = fileName; } else { 
    if (res.headers["content-disposition"]) { 
    const contentDisposition = res.headers["content-disposition"].split("="); name = (contentDisposition && decodeURI(contentDisposition[1])) || ""; } } const file = new File([res.data], res.data); const href = URL.createObjectURL(file); const aTag = document.createElement("a"); aTag.download = name; aTag.target = "_blank"; aTag.href = href; aTag.click(); URL.revokeObjectURL(href); } 
2.1、直接使用接口

1、页面文件

index.vue

<el-table-column align="center" label="相关附件" prop="fileName"> <template #default="scope"> <span style="color: #409eff; cursor: pointer" @click="handelDowload(scope.row)">{ 
  {scope.row.fileName}}</span> </template> </el-table-column> <script lang="ts" setup> import axios from '@/utils/request' const handelDowload = (row: any) => { console.log(row); axios({ method: 'POST', url: process.env.VUE_APP_API_HOST + constant.fileUpload + '/download?id=' + file.fileId, responseType: 'blob' }) .then(result => { const content = result.data const blob = new Blob([content]) const fileName = file.fileName if ('download' in document.createElement('a')) { const elink = document.createElement('a') elink.download = fileName elink.style.display = 'none' elink.href = URL.createObjectURL(blob) document.body.appendChild(elink) elink.click() URL.revokeObjectURL(elink.href) document.body.removeChild(elink) } else { navigator.msSaveBlob(blob, fileName) } }) } </script> 
2.2、抽离使用接口-post

1、页面文件

index.vue

<script setup> import { getHomePageMenuListApi,getSpecialMenuListApi } from '@/api/prefecture' const getMenuList = async() => { try { let result = await getHomePageMenuListApi({ siteId: sessionStorage.getItem('siteId') }) if (result.data.code == 200) { tabList.value = result.data.data.filter(item => item.title == '门户网站')[0].children } } catch (error) { } } const demoMethod = () => { getSpecialMenuListApi({}).then((res) => { this.specialMenuList = res.data.data }) } onMounted(() => { demoMethod() getMenuList() }) </script> 

2、接口文件

src\api\prefecture\index.js

import axios from '@/utils/request' import { 
    getApiUrl } from "@/utils/tool"; import constant from "@/components/constant"; const baseUrl = getApiUrl(); // 获取首页菜单列表根据专区id export const getHomePageMenuListApi = (params) =>{ 
    return axios.post(baseUrl + constant.publicCoop + '/menu/treeList',params) } // 获取特色专区导航菜单 export const getSpecialMenuListApi = (params) =>{ 
    return axios.post(baseUrl + constant.publicCoop + '/navigation/special/get',params) } 

基准地址

src\utils\tool.js

export function getApiUrl(v) { 
    return process.env.VUE_APP_API_HOST } 

根目录文件

.env.dev

NODE_ENV = 'development' VUE_APP_API_HOST = '/gp' VUE_APP_IMAGE_HOST = 'http://27.196.114.67:18081' 

vue.config.js

const { 
    defineConfig } = require('@vue/cli-service') const AutoImport = require('unplugin-auto-import/webpack') const Components = require('unplugin-vue-components/webpack') const { 
    ElementPlusResolver } = require('unplugin-vue-components/resolvers') module.exports = defineConfig({ 
    transpileDependencies: true, lintOnSave: false, devServer: { 
    proxy: { 
    '/gp': { 
    target: 'http://27.196.111.15:18080', // 后端ip地址 changeOrigin: true, pathRewrite: { 
    '^/gp': '/' } }, }, port: 9000, // host:'27.196.114.112', //前端本地ip地址 host:'0.0.0.0', open:true }, }) 

网关标识

src\components\constant.js

/ * Created by author on 2023/12/15. */ export default { 
    ieopCollaborate: "/ieop-mtg-collaborate", // 在线协作网关标识 ieopMtgUnion: "/ieop-mtg-union", // 创新网关标识 ieopKnowledge: "/ieop-knowledge", // 知识交流网关标识 publicCoop: "/ieop-mtg-coop", // 公共网关标识 } 
2.3、get请求

index.vue

<script> // import axios from '@/utils/request' import axios from "axios"; axios.get(process.env.VUE_APP_API_HOST+ "/messageSum/total") .then((res) => { if (res.data.result == 0) { useUserStore().state.newsNumber = res.data.data; el.innerHTML = res.data.data; } else { ElMessage.error(res.data.hint); } }) .catch((err) => { // ElMessage.error('获取数据失败!') }) </script> 
到此这篇vue3中,axios的几种用法之抽离接口、post请求、get请求、.env.dev、网关标识、基准地址的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!

版权声明


相关文章:

  • vue中provide和inject的用法2024-11-30 21:00:10
  • vue3中,渲染动态表单(一)——定义公共样式、使用动态样式class & 抽离el-dialog对话框组件 & 父子传参 & 自定义slot插槽 & vue3中watch写法和computed写法2024-11-30 21:00:10
  • vue3中,渲染动态表单(二)——使用wangEditor组件 & vue3基础页面的写法之defineComponent、toRefs、reactive和return & main文件注册全局组件2024-11-30 21:00:10
  • vue3中,渲染动态表单(三)——梳理动态表单的几种类型、树结构表格row-key、父子传值之props、emit和defineEmits & ElLoading组件用法和post请求动态地址2024-11-30 21:00:10
  • vue3,下载预览的四种方法之responseType-blob、fileName、a标签下载& axios之post请求写法& 引入js方法文件写法& try和catch、async和await用法2024-11-30 21:00:10
  • tsconfig.json配置释义2024-11-30 21:00:10
  • JSON的几种注释2024-11-30 21:00:10
  • Vue中失去焦点时所触发的事件2024-11-30 21:00:10
  • vue中,动态绑定样式——动态绑定style写法 & 动态class写法2024-11-30 21:00:10
  • vue中this.$route.query和this.$route.params & query传参和params传参的使用和区别2024-11-30 21:00:10
  • 全屏图片