Skip to content

添加全局指令

创建全局指定文件

  • utils/globalzhiling.js
js
import dayjs from "dayjs";

const dateFilter = (val, format = "YYYY-MM-DD") => {
  if (!isNaN(val)) {
    val = parseInt(val);
  }

  return dayjs(val).format(format);
};

export default (app) => {
  app.config.globalProperties.$tools = {
    dateFilter,
  };
};

绑定到全局

  • main.js
js
// 引入 时间戳
import installFilter from "@/utils/globalzhiling.js";

// 绑定自定是指令
installFilter(app);

使用

  • 组件里面使用
html
<el-table-column prop="openTime" label="创建时间" align="center">
  <template #default="{ row }">
    {{ $tools.dateFilter(row.openTime) }}
  </template>
</el-table-column>

JS 中使用

vue
<template>
  <div>
    <Header></Header>
    <el-button type="primary">Primary</el-button>
    {{ $tools.dateFilter(parseInt("1737445049576")) }}
    <Footer></Footer>
  </div>
</template>

<script setup>
import { getCurrentInstance } from "vue";

const instance = getCurrentInstance();

const time = instance.appContext.config.globalProperties.$tools.dateFilter(
  parseInt("1737445049576")
);
console.log(time);
</script>

<style lang="scss" scoped></style>