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配置全局参数及组件的使用方法的详细内容,更多请关注【创想鸟】其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/3230010.html

(0)
上一篇 2025年4月1日 16:26:16
下一篇 2025年4月1日 16:26:25

AD推荐 黄金广告位招租... 更多推荐

相关推荐

发表回复

登录后才能评论