vue3挂载全局方法

本文介绍了如何在JavaScript项目中创建一个名为`tool.js`的模块,包含常用方法,然后在Vue应用中全局引入并利用`$TOOLS`变量方便地调用。通过`setup`中的`proxy`实现组件内快速访问这些工具函数。

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

1.方法挂在到全局

比如某个js方法,项目很多地方都能用到,每次去重新写一遍太麻烦,放在一个js里面,每次去引入也懒得引,就可以挂载在全局上

1.创建tool.js文件,里面放常用的方法

const tools = {
  getCurrentTim(){
    const currentTime = new Date();
    const year = currentTime.getFullYear();
    const month = currentTime.getMonth() + 1; // 月份从0开始,因此需要加1
    const day = currentTime.getDate();
    const hours = currentTime.getHours();
    const minutes = currentTime.getMinutes();
    const seconds = currentTime.getSeconds();
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  },
  xxxx(){},
}
export default tools;

2.在main.js引入

import tools from './tools';

const app = createApp(App)
app.config.globalProperties.$TOOLS = tools;
...

3.vue页面使用

//从vue引入getCurrentInstance方法
 import { defineComponent, ref, reactive, watchEffect, getCurrentInstance, toRefs } from 'vue';
//定义setup 里面定义proxy
 setup(props, ctx) {
    const { proxy } = getCurrentInstance();
    // 设备类型
    const deviceType = 'sblxZyb';
    // 下拉列表
    let selectState = reactive({
      time: proxy.$TOOLS.getCurrentTim(),
      ASSET_UNIT_LIST: [],
 });

2.祖孙组件之间传参

provide 和 inject
用法:

爷爷组件:

const operBtnShow = ref(true)
provide('operBtnShow', operBtnShow)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值