VUE2中可以将我们需要的插件挂载到VUE的主链上(配置成全局属性),然后通过this调用,但是在VUE3的ts中使用这样的配置方法的话是没法通过编译的,这个时候我们就需要拓展属性。

// 下面是在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 配置全局axios属性

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");

全局axios使用:

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: guanchao_gc@qq.com
         * @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: guanchao_gc@qq.com
         * @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: guanchao_gc@qq.com
         * @date: 2021-01-10 
         */
        const dataRef = toRefs(data);
        return {
            getData,
            ...dataRef
        }
    },//*/
};

当然,官方是不建议将axios或者router这些插件挂载到主链上的,因此,我这里只是尝试了一下这样的可能,但是不建议这样使用。

有好的建议,请在下方输入你的评论。

欢迎访问个人博客
https://guanchao.site

欢迎访问小程序:

在这里插入图片描述

Logo

前往低代码交流专区

更多推荐