vue3配置全局参数(挂载全局方法)以及组件的使用
更新时间:2022年07月21日 09:39:57 作者:温情key
这篇文章主要介绍了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)
在appContext.config.globalProperties里面已经可以看到挂载的$messageBox和$message1了,至于为什么还有一个$message
我们可以看张element plus官网的截图
可以看到这是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 } } })
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
ElementUI级联选择器实现同一父级下最多只能选中一个子级
本文主要介绍了ElementUI级联选择器实现同一父级下最多只能选中一个子级,同一父级下的子节点单选,又可以选择多个不同父级下的节点,具有一定参考价值,感兴趣的可以了解一下2023-10-10uniapp 小程序和app map地图上显示多个酷炫动态的标点效果(头像后端传过来)
这篇文章主要介绍了uniapp 小程序和app map地图上显示多个酷炫动态的标点效果(头像后端传过来),本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-09-09
最新评论