vue3 挂载全局对象,如何在组件内使用?

本文详细介绍了在Vue2和Vue3中如何全局挂载方法,包括Vue2的原型扩展和Vue3的组合式API使用。在Vue2中,通过Vue.prototype.$http挂载自定义方法;而在Vue3中,通过createApp配置globalProperties来挂载$Methods、$CONFIG和$TOOL,并在组件内部利用getCurrentInstance获取并使用这些全局对象。示例中展示了时间格式化和数组去重的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:vue2挂载方法:

Vue.prototype.$http = http
//在对应的组件中使用
this.$http

2:vue3挂载方法:

// 全局挂载
const app = createApp(App)
app.config.globalProperties.$Methods = Methods;
//挂载全局对象
app.config.globalProperties.$CONFIG = config;
app.config.globalProperties.$TOOL = tool;
//在组件内使用
import { ref, reactive, onMounted,getCurrentInstance } from "vue";

//vue3是组合式API,所以要引入 getCurrentInstance 
const { proxy } = getCurrentInstance();
const $TOOL = proxy.$TOOL;
const $Methods = proxy.$Methods;


//时间格式化
inputValue.value = $TOOL.dateFormat(inputValue.value, 'yyyy-MM-dd hh:mm:ss')
//数组去重
 const jsonarrreduce = reactive([
      { id: "1", name: "李白" },
      { id: "2", name: "杜甫" },
      { id: "3", name: "白居易" },
      { id: "4", name: "项羽" },
      { id: "5", name: "小米" },
      { id: "1", name: "红米" },
      { id: "1", name: "诺基亚" },
      { id: "2", name: "真我" },
    ]);
    onMounted(() => {
      console.log($Methods.JsonArrReduce(jsonarrreduce, "id"));
    });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值