VUE3 (thirteen) introduce axios globally in main.ts

In VUE2, we can mount the plug-in we need to the main chain of VUE (configured as a global property), and then call it through this, but if you use this configuration method in VUE3's ts, it cannot be compiled. At this time, we You need to expand the attributes.

// 下面是在vue3.0定义源文件找到的一段说明注释
/**
 * Custom properties added to component instances in any way and can be accessed through `this`
 *
 * @example
 * Here is an example of adding a property `$router` to every component instance:
 * ```ts
 * import { createApp } from 'vue'
 * import { Router, createRouter } from 'vue-router'
 *
 * declare module '@vue/runtime-core' {
 *   interface ComponentCustomProperties {
 *     $router: Router
 *   }
 * }
 *
 * // effectively adding the router to every component instance
 * const app = createApp({})
 * const router = createRouter()
 * app.config.globalProperties.$router = router
 *
 * const vm = app.mount('#app')
 * // we can access the router from the instance
 * vm.$router.push('/')
 * ```
 */
}

vue3.x+typescript configures global axios attributes

import {
    
     createApp } from 'vue'
import App from './App.vue'
import route from './route'
//配置Antd
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
 
//配置请求数据
import {
    
    AxiosInstance } from "axios";
import Axios from "axios";
 
//全局配置Axios
declare module '@vue/runtime-core' {
    
    
    interface ComponentCustomProperties {
    
    
      $axios: AxiosInstance;
    }
}
let app=createApp(App)
app.config.globalProperties.$axios=Axios;  //this.Axios
app.use(route)
app.use(Antd)
app.mount('#app')

main.js

// 引入vue3中vue框架的createApp这个方法,创建一个实例
import {
    
     createApp } from "vue";
// 引入vuex
import store from "/@/store";
 
// ======================================================
// 引入路由
import {
    
     Router } from 'vue-router'
import router from "/@/router";
 
// import ElementPlus from 'element-plus';
// import '../node_modules/element-plus/lib/theme-chalk/index.css';
// import Antd from "ant-design-vue";
// import "../node_modules/ant-design-vue/dist/antd.css";
 
//配置请求数据
import {
    
     AxiosInstance } from "axios";
// 引入自定义封装的axios
import axios from "./hooks/axios";
 
// =======================================================
//全局配置axios,router (typescript使用)
declare module '@vue/runtime-core' {
    
    
    interface ComponentCustomProperties {
    
    
        $axios: AxiosInstance;
        $router: Router;
    }
}
 
import App from "/@/App.vue";
 
// 创建实例
const app = createApp(App);
app.use(router);
app.use(store);
 
// =======================================================
// vue3版本的全局函数
// === Vue.prototype.name = 'vue2'
app.config.globalProperties.$axios = axios;  
app.config.globalProperties.$router = router;
// 调用
/**
    import {getCurrentInstance,} from "vue";
    //获取上下文实例,ctx=vue2的this
    const { ctx } = getCurrentInstance();
    ctx.$router.push('/xxx/xxxx');
 */
 
// =======================================================
// 加载UI框架
// app.use(Antd);
// app.use(ElementPlus);
 
// 将实例挂载至节点
app.mount("#app");

Global axios use:

Index.ts

import {
    
    
    PropType,
    ref,
    watch,
    reactive,
    toRefs,
    getCurrentInstance,
    provide,
    inject,
    onBeforeMount,// 在组件挂载之前执行的函数
    onMounted,
    onBeforeUpdate,// 在组件修改之前执行的函数
    onUpdated,
    onBeforeUnmount,// 在组件卸载之前执行的函数
    onUnmounted,
    nextTick
} from "vue";
// 引入axios钩子
import axios from "/@/hooks/axios.ts";
// 引入路由
import {
    
     useRouter, useRoute } from "vue-router";
 
// 引入各个自定义组件
import HelloWorld from "/@/components/HelloWorld.vue";
import Footer from "/@/components/pc/Footer.vue";
import Header from "/@/components/pc/Header.vue";
import Menu from "/@/components/pc/Menu.vue";
import load from "/@/components/pc/loading.vue";
import TopIM from "/@/components/pc/TopIM.vue";
import Drawer from "/@/components/pc/Drawer.vue";
import Pagination from "/@/components/pc/Pagination.vue";
 
// 引入公共js文件
import utils from "/@/assets/js/public/function";
// 公共状态文件
import {
    
     common } from "/@/hooks/common.ts";
export default {
    
    
    name: "index",
    components: {
    
    
        HelloWorld,
        Footer,
        Header,
        Menu,
        load,
        TopIM,
        Drawer,
        Pagination,
    },
    // VUE3 语法 第一个执行的钩子函数
    // setup官方文档 :https://www.vue3js.cn/docs/zh/guide/composition-api-setup.html#参数
    // setup(props: any, content: any) {
    
    
    setup(props: any, content: any) {
    
    
        const router = useRouter();
        const route = useRoute()
        //获取上下文实例,ctx=vue2的this
        const {
    
     ctx,proxy } = getCurrentInstance();
        /**
         * @name: 声明data
         * @author: camellia
         * @email: [email protected]
         * @date: 2021-01-10 
         */
        const data = reactive({
    
    
            // 展示menu
            showRef: 0,
            // 全局参数
            glabl: common.glabl,
            // loading 是否显示
            loading: true,
            // 文章列表
            articleList:[],
            // 数据页数
            articlePage:0,
            // 当前页
            currentPage: route.query.page ? route.query.page : 1,
            // 分页显示页码数
            dataNum:7,
            // 查询条件
            search:'search',
            // 数据总条数
            dataDatanum:'',
        });
        /**
         * @name: 获取页面数据
         * @author: camellia
         * @email: [email protected]
         * @date: 2021-01-13 
         * @param:  data    type    description
         * @return: data    type    description
         */
        const getData = (sign:string = '') => {
    
    
            // 文档 :http://www.axios-js.com/zh-cn/docs/
            let param = {
    
    
                page: data.currentPage
            };
            data.loading = true;
            proxy.$axios.get('/index.php/index/getdata', {
    
     params: param})
            //axios.get('/index.php/index/getdata', { params: param })
            .then(function (response:any) {
    
    
                data.articlePage = response.data.articlePage;
                data.articleList = response.data.articleShow;
                data.dataDatanum = response.data.dataDatanum;
                data.loading = false;
 
                // 回到滚动条刷新前位置
                if (sign)
                {
    
    
                    let currectWidth = window.screen.height;
                    if (currectWidth == 1080)
                    {
    
    
                        utils.goToScrollTop(968);
                    }
                    else
                    {
    
    
                        utils.goToScrollTop(650);
                    }
                }
                else
                {
    
    
                    utils.goToScrollTop();
                }
            })
            .catch(function (error:any) {
    
    });
        }
 
        
        // 初始调用
        getData();
 
        /**
         * @name: 将data绑定值dataRef
         * @author: camellia
         * @email: [email protected]
         * @date: 2021-01-10 
         */
        const dataRef = toRefs(data);
        return {
    
    
            getData,
            ...dataRef
        }
    },//*/
};

Of course, the official does not recommend mounting plug-ins such as axios or router to the main chain. Therefore, I just tried such a possibility here, but it is not recommended to use it in this way.

Have a good suggestion, please enter your comment below.

Welcome to personal blog
https://guanchao.site

Welcome to the Mini Program:

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39708228/article/details/114662431