vue3配置全局參數(shù)(掛載全局方法)以及組件的使用
vue2的方式
1. 全局掛載
Vue.property.xxx
import Vue from "vue"; import axios from "axios"; Vue.prototype.$http= axios; new Vue({ ? router, ? store, ? render: (h) => h(App), }).$mount("#app");
2. 組件使用
this.$http.xxx();
vue3的方式
1. 全局掛載
app.config.globalProperties.xxx
import { createApp } from 'vue' import App from './App.vue' import ElementPlus, { ElMessage, ElMessageBox } from 'element-plus' import 'element-plus/dist/index.css' const app = createApp(App); app.config.globalProperties.$messageBox = ElMessageBox; app.config.globalProperties.$message1 = ElMessage;
2. 組件使用
// 引入vue的 getCurrentInstance 方法 import { defineComponent, getCurrentInstance } from "vue"; // 獲取當前組件實例 const { appContext } = getCurrentInstance(); // 打印看一下結(jié)構(gòu) console.log(appContext)
在appContext.config.globalProperties里面已經(jīng)可以看到掛載的$messageBox和$message1了,至于為什么還有一個$message
我們可以看張element plus官網(wǎng)的截圖
可以看到這是element plus默認掛載的,我們可以直接使用,這里添加$message1只是演示,其實是可以直接使用默認掛載的。
完整使用例子
// 引入vue的 getCurrentInstance 方法 import { defineComponent, getCurrentInstance } from "vue"; // 獲取當前組件實例 const { appContext } = getCurrentInstance(); const globalProxy = appContext.config.globalProperties; export default defineComponent({ setup() { // 退出登錄按鈕 const loginOut = () => { globalProxy.$messageBox.confirm("確定退出登錄嗎?", "提示", { confirmButtonText: "確定", cancelButtonText: "取消", type: "warning", }) .then(() => { setTimeout(() => { globalProxy.$message1({message: "已退出登錄", type: "success"}); localStorage.removeItem("userInfo"); router.push("/login"); }, 200); }) .catch((e) => { console.log(e); }); }; return { loginOut } } })
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue使用html2canvas實現(xiàn)截取圖片并保存
html2canvas是一個JavaScript庫,它可以將HTML元素轉(zhuǎn)換為Canvas元素本文將介紹一下Vue如何使用html2canvas實現(xiàn)截取圖片并保存功能,需要的可以參考下2023-12-12vue+elementui實現(xiàn)動態(tài)控制表格列的顯示和隱藏
這篇文章主要介紹了vue+elementui實現(xiàn)動態(tài)控制表格列的顯示和隱藏,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04vue+echarts實現(xiàn)中國地圖流動效果(步驟詳解)
這篇文章主要介紹了vue+echarts實現(xiàn)中國地圖流動效果(步驟詳解),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01ElementUI級聯(lián)選擇器實現(xiàn)同一父級下最多只能選中一個子級
本文主要介紹了ElementUI級聯(lián)選擇器實現(xiàn)同一父級下最多只能選中一個子級,同一父級下的子節(jié)點單選,又可以選擇多個不同父級下的節(jié)點,具有一定參考價值,感興趣的可以了解一下2023-10-10uniapp 小程序和app map地圖上顯示多個酷炫動態(tài)的標點效果(頭像后端傳過來)
這篇文章主要介紹了uniapp 小程序和app map地圖上顯示多個酷炫動態(tài)的標點效果(頭像后端傳過來),本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09