vue3挂载全局方法

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

你可能感兴趣的:(vue.js,javascript,前端)