0.2.0 • Published 2 years ago
module-filters v0.2.0
安装
npm install module-filters -D
or
yarn add module-filters -D
环境
推荐 node 14 或以上
工具库列表
export {
copyToClipboard, // 复制到剪贴板
shuffle, // 数组重排
randomHexColor, // 生成随机的16进制颜色
currency, // 加币种符号,格式化千分位
formatDate, // 时间戳转日期格式
formatDateTimestamp, // 日期格式转时间戳
code2text, // 数据状态码翻译
percentage, // 格式化百分比
truncate, // 截断文字
eraserEmpty, // 格式化空数据
deepCloneArr // 深复制数组
};
vue2 中应用
全局安装
在 main.js 中登记
import Vue from "vue";
import App from "@/App";
import * as filters from "module-filters";
Object.keys(filters).forEach((key) => {
Vue.filter(key, filters[key]);
});
new Vue({
el: "#app",
render: (r) => r("App"),
components: {
App
}
});
例如使用 currency 方法:
<template>
<div>
<!-- 输出 "¥1,000.00" 字符串 -->
{{ 1000 | currency("¥") }}
</div>
</template>
<script>
export default {
created() {
console.log(this.$options.filters.currency(1000, "¥")); // 输出 "¥1,000.00" 字符串
}
};
</script>
*.vue 中按需加载
import { currency } from "module-filters";
例如使用 currency 方法:
<template>
<div>
<!-- 输出 "¥1,000.00" 字符串 -->
{{ 1000 | currency("¥") }}
</div>
</template>
<script>
import { currency } from "module-filters";
export default {
filters: {
currency
},
created() {
console.log(currency(1000, "¥")); // 输出 "¥1,000.00" 字符串
}
};
</script>
vue3 中应用
全局安装
在 main.js 中登记
import { createApp } from "vue";
import App from "./App.vue";
const app = createApp(App);
import * as filters from "module-filters";
// vue3 舍弃了 filter 属性,用注册全局方法代替
app.config.globalProperties.$filters = filters;
app.mount("#app");
例如使用 currency 方法:
<template>
<div>
<!-- 输出 "¥1,000.00" 字符串 -->
{{ $filters.currency(1000, "¥") }}
</div>
</template>
<script setup>
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const formatCurrency = () => {
console.log('currency: ', proxy.$filters.currency(1000, "¥"));
};
</script>
*.vue 中按需加载
import { currency } from "module-filters";
例如使用 currency 方法:
<template>
<div>
<!-- 输出 "¥1,000.00" 字符串 -->
{{ currency(1000, "¥") }}
</div>
</template>
<script setup>
import { currency } from "module-filters";
const formatCurrency = () => {
console.log(currency(1000, "¥")); // 输出 "¥1,000.00" 字符串
};
</script>
code2text
code2text(code, data, value, label);
参数 | 说明 | 类型 | 可选值 | 默认值 |
---|---|---|---|---|
code | 要翻译的值 | - | - | - |
data | 要参照的数据集 | Array | - | - |
value | 要校对的数据集的 key | String | - | 'value' |
label | 要返回的数据集的 key | String | - | 'label' |
例子:
const arr = [
{
age: 12,
name: 'Ray',
weight: '190 kg'
},
{
age: 28,
name: 'Ally',
weight: '10 kg'
}
]
code2text(12, arr, age, name); // return 'Ray'
...