vue3配置全局参数及组件的使用方法

发布时间:2022-07-21 11:51:15 作者:iii
来源:亿速云 阅读:180

本篇内容主要讲解“vue3配置全局参数及组件的使用方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“vue3配置全局参数及组件的使用方法”吧!

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();
// 打印看一下结构
console.log(appContext)

vue3配置全局参数及组件的使用方法

在appContext.config.globalProperties里面已经可以看到挂载的$messageBox和$message1了,至于为什么还有一个$message

我们可以看张element plus官网的截图

vue3配置全局参数及组件的使用方法

可以看到这是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
 	 }
   }
})

到此,相信大家对“vue3配置全局参数及组件的使用方法”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. vue全局组件与局部组件使用方法详解
  2. 如何使用use注册Vue全局组件和全局指令

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue3

上一篇:linux栈指的是什么

下一篇:JavaScript实现继承的常用方式有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》