赞
踩
1、axios全局配置
vue2中使用的是
Vue.prototype.$axios = axios
然后在组件中使用this调用
this.$axios
vue3中没有this,可以有两种方式绑定全局
app.config.globalProperties.$axios = axios
在组件中使用getCurrentInstance()方法获取实例后调用
- const internalInstance = getCurrentInstance().appContext.config.globalProperties
-
- internalInstance.$axios
-
官方不推荐上述方式
注:当使用getCurrentInstance().appContext.config.globalProperties.$axios
getCurrentInstance().appContext.config.globalProperties!.$axios
时,ts编译器会报错,可以加个!符号来处理报错问题。
第二种是使用vue-axios,安装依赖
npm install vue-axios
在main.ts中使用,并注入axios实例
- app.use(VueAxios, axios);
-
- app.provide('axios', app.config.globalProperties.axios)
在组件中使用
- import {reactive,inject} from 'vue'
- const axios:any = inject('axios')
2、vite.config.ts
使用自动导入,需要安装两个包
npm install -D unplugin-vue-components unplugin-auto-import
添加import参数
- AutoImport({
- resolvers: [ElementPlusResolver()],
- imports:['vue','vue-router']
- }),
则会自动在auto-imports.d.ts中导入
在组件中使用时,无需在import就能直接使用了
- <script setup lang="ts">
- // import {useRouter} from "vue-router";
- // import {reactive,inject} from 'vue'
-
- const router = useRouter();
- const input = reactive({
- username: "",
- password: ""
- })
- const axios:any = inject('axios')
- const login = function () {
- axios.post('/login', input).then((res: any) => {
- if (res.data.code === 200) {
- router.push('/index')
- } else {
- }
- }).catch((err: any) => {
- console.log(err)
- })
- }

3、vite.config.ts跨域设置
- server: {
- port:3000,
- proxy: {
- '/api': {
- target: 'http://localhost:8443',
- changeOrigin: true,
- // rewrite: (path) => path.replace(/^\/api/, '')
- },
- }
- },
4、vite.config.ts设置@
- resolve: {
- // 配置路径别名
- alias: {
- '@': path.resolve(__dirname, './src'),
- },
- },
5、vite.config.ts require方式导入path,报错问题
需要安装@types/node
npm i --save-dev @types/node
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。