Vue 3 + TypeScript 项目中全局挂载并使用工具函数

一、proxy方式

1.封装日期选择工具函数:

在untils文件夹下新建index.ts,并导出工具函数

javascript 复制代码
/**
 * 获取不同类型日期
 * param:类型 dateVal: 是否指定
 */
export function getSystemDate(param: any, dateVal: any) {
  let systemDate = dateVal ? new Date(dateVal) : new Date(),
    year = systemDate.getFullYear(),
    month = systemDate.getMonth() + 1,
    date = systemDate.getDate(),
    hours = systemDate.getHours(),
    minutes = systemDate.getMinutes(),
    seconds = systemDate.getDate(),
    milliseconds = systemDate.getMilliseconds();
  month = month < 10 ? "0" + month : month;
  date = date < 10 ? "0" + date : date;
  hours = hours < 10 ? "0" + hours : hours;
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;
  if (param == 0) {
    return year + "-" + month + "-" + date;
  } else if (param == 1) {
    return year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
  } else if (param == 2) {
    return year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds + "." + milliseconds;
  } else if (param == 3) {
    return year + "-" + month;
  } else if (param == 4) {
    return year;
  }
}

2.引入并挂载到全局

在main.ts中,引入后挂载

javascript 复制代码
import { App, createApp } from "vue";
import App from "./App.vue";

import { getSystemDate } from "@/utils/index"; //引入全局使用的方法

const app = createApp(App);

app.config.globalProperties.$getSystemDate = getSystemDate; //挂载到全局

app.mount("#app");

注意:

1.vue3中挂载实例要用app.config.globalProperties.方法,而vue2中挂载实例是Vue.prototype.方法;

3.在页面中按需调用

template部分代码:

html 复制代码
<template>
  <div>
      <el-date-picker
          v-model="plantInfo.gridDate"
          type="date"
          placeholder="选择日期"
          :disabled-date="disabledDate"
          :shortcuts="shortcuts"
          format="YYYY-MM-DD"
          style="width: 100%"
      />
  </div>
</template>

script 中代码:

html 复制代码
<script setup lang="ts" name="site">
import { ref, reactive, getCurrentInstance } from "vue";

// proxy相当于 vue2的this,从getCurrentInstance 实例中获取,proxy对象
const { proxy } = getCurrentInstance();

interface PlantInfo {
  plantName: any;
  plantScale: any;
  sysuserid: any;
  userDepid: any;
  gridDate: any;
  plantNetType: any;
  voltageLevel: any;
  prjAddr: any;
  longitude: any;
  moduleManufacturer: any;
  componentBrand: any;
  componentModel: any;
  workHours: any;
  plantStatus: any;
  roofPitch: any;
  orientation: any;
  plantShip: any;
  plantType: any;
  streetAddress: any;
  plantSummary: any;
  plantImageUrl: any;
  plantInvestor: any;
}

const plantInfo = ref<PlantInfo>({
  plantName: "",
  plantScale: "",
  sysuserid: "",
  userDepid: "",
  gridDate: proxy.$getSystemDate(0),
  plantNetType: "",
  voltageLevel: "",
  prjAddr: "",
  longitude: "",
  moduleManufacturer: "",
  componentBrand: "",
  componentModel: "",
  workHours: "",
  plantStatus: "",
  roofPitch: "",
  orientation: "",
  plantShip: "",
  plantType: "",
  streetAddress: "",
  plantSummary: "",
  plantImageUrl: "",
  plantInvestor: ""
});

const disabledDate = (time: Date) => {
  return time.getTime() > Date.now();
};
// 快速日期选择属性
const shortcuts = [
  {
    text: "今天",
    value: new Date()
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    }
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    }
  }
];
</script>

二、provide方式

在Vue 3 + TypeScript 中挂载并使用一个全局的工具函数,你可以通过 Vue 实例的 provideinject 方法来实现。具体步骤如下:

1.创建工具函数: 首先,创建你的工具函数。

javascript 复制代码
// utils.ts
export function myUtilityFunction(): void {
  // Your utility function logic here
}

2.在主入口文件中挂载工具函数: 在 Vue 的主入口文件中,将工具函数通过 provide 方法挂载到全局。

javascript 复制代码
// main.ts
import { createApp } from 'vue';
import App from './App.vue';
import { myUtilityFunction } from './utils';

const app = createApp(App);

// 将工具函数挂载到全局
app.provide('myUtility', myUtilityFunction);

app.mount('#app');

3.在组件中使用工具函数: 在需要使用工具函数的组件中,通过 inject 方法注入并使用该函数。

javascript 复制代码
<!-- MyComponent.vue -->
<template>
  <div>
    <button @click="useUtility">使用工具函数</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, inject } from 'vue';

export default defineComponent({
  setup() {
    // 注入工具函数
    const myUtility = inject<() => void>('myUtility');

    const useUtility = () => {
      // 使用工具函数
      myUtility();
    };

    return {
      useUtility
    };
  }
});
</script>
相关推荐
呆呆的小草2 小时前
Cesium距离测量、角度测量、面积测量
开发语言·前端·javascript
WHOAMI_老猫2 小时前
xss注入遇到转义,html编码绕过了解一哈
javascript·web安全·渗透测试·xss·漏洞原理
一 乐3 小时前
民宿|基于java的民宿推荐系统(源码+数据库+文档)
java·前端·数据库·vue.js·论文·源码
BillKu4 小时前
Vue3 + TypeScript + Element Plus 表格行按钮不触发 row-click 事件、不触发勾选行,只执行按钮的 click 事件
vue.js·elementui·typescript
小前端大牛马4 小时前
react中hook和高阶组件的选型
前端·javascript·vue.js
刺客-Andy4 小时前
React第六十二节 Router中 createStaticRouter 的使用详解
前端·javascript·react.js
秋田君5 小时前
深入理解JavaScript设计模式之策略模式
javascript·设计模式·策略模式
萌萌哒草头将军6 小时前
🚀🚀🚀VSCode 发布 1.101 版本,Copilot 更全能!
前端·vue.js·react.js
菜鸡爱上编程7 小时前
React16,17,18,19更新对比
前端·javascript·reactjs·react
我命由我123457 小时前
VSCode - VSCode 转换英文字母的大小写
开发语言·javascript·ide·vscode·编辑器·html·软件工具