溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue3怎么配置全局參數(shù)及組件

發(fā)布時(shí)間:2023-05-19 15:44:19 來源:億速云 閱讀:146 作者:iii 欄目:編程語言

這篇“vue3怎么配置全局參數(shù)及組件”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“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";
// 獲取當(dāng)前組件實(shí)例
const { appContext } = getCurrentInstance();
// 打印看一下結(jié)構(gòu)
console.log(appContext)

vue3怎么配置全局參數(shù)及組件

在appContext.config.globalProperties里面已經(jīng)可以看到掛載的$messageBox和$message1了,至于為什么還有一個(gè)$message

我們可以看張element plus官網(wǎng)的截圖

vue3怎么配置全局參數(shù)及組件

可以看到這是element plus默認(rèn)掛載的,我們可以直接使用,這里添加$message1只是演示,其實(shí)是可以直接使用默認(rèn)掛載的。

完整使用例子

// 引入vue的 getCurrentInstance 方法
import { defineComponent, getCurrentInstance } from "vue";
// 獲取當(dāng)前組件實(shí)例
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
 	 }
   }
})

以上就是關(guān)于“vue3怎么配置全局參數(shù)及組件”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI