vue3挂载全局方法

2023-12-20 15:37:23

比如某个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: [],
 });

文章来源:https://blog.csdn.net/Web_Notes/article/details/135106789
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。