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、网关标识、基准地址的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/qdvuejs/10702.html