Skip to content

JavaScript 实用技巧

toLocaleString 妙用

js
(1234567).toLocaleString()               // "1,234,567" 千分位
(1234567).toLocaleString('zh-CN-u-nu-hanidec')  // "一,二三四,五六七" 中文数字
new Date().toLocaleString('zh-CN')       // 本地化日期时间

比正则替换更简洁、国际化友好。注意不同浏览器实现有微小差异。

千位分隔符(4 种方法)

  1. (n).toLocaleString() — 最简洁
  2. n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') — 正则法
  3. Intl.NumberFormat().format(n) — 国际化 API
  4. 手动循环 — 性能最优但代码多

日常开发直接用 toLocaleStringIntl.NumberFormat 即可。

剪贴板 API

js
// 写入
navigator.clipboard.writeText('复制的内容').catch(() => {});

// 读取(需用户授权)
const text = await navigator.clipboard.readText();

注意: navigator.clipboard 只在 HTTPS 或 localhost 下可用,HTTP 页面上返回 undefined

JS 小数精度丢失

0.1 + 0.2 !== 0.3。原因:JS 使用 IEEE 754 双精度浮点数。解决方案:金额用分、toFixed()、decimal.js / big.js。

"准确"的倒计时

setInterval 不精确,long-running 有累积误差。解决方案:每次执行时用 Date.now() 减去目标截止时间算剩余时间,setInterval 只负责触发重算。

修改 URL 参数不刷新页面

js
const url = new URL(window.location);
url.searchParams.set('key', 'value');
window.history.replaceState({}, '', url);

JS 时间戳获取方法

5 种:Date.now(), new Date().getTime(), new Date().valueOf(), +new Date(), Number(new Date())。Date.now() 性能最优。

正则格式化手机号

js
'13812345678'.replace(/(\d{3})(\d{4})(\d{4})/, '$1 $2 $3')
// "138 1234 5678"

Vuex 数据刷新丢失

问题: Vuex 存内存,刷新全丢。

方案:

  • vuex-persistedstate 插件,自动同步到 localStoragesessionStorage
  • 手动在 beforeunload 时保存,created 时恢复
  • 只用 Vuex 存临时状态,持久数据放 localStorage + 后端 API 重新获取

Vue 3 自定义 Hooks

将可复用逻辑抽成 useXxx 函数,类似 React Hooks 的思想:

js
function useMouse() {
  const x = ref(0), y = ref(0);
  const handler = (e) => { x.value = e.x; y.value = e.y; };
  onMounted(() => window.addEventListener('mousemove', handler));
  onUnmounted(() => window.removeEventListener('mousemove', handler));
  return { x, y };
}

可视化大屏自适应:vue-autofit

一行搞定自适应缩放:

html
<autofit>
  <div>大屏内容</div>
</autofit>

基于 transform: scale 等比缩放,比手动计算 vw/vh 方便太多。

Vue watch 仅监听一次

使用 this.$watch 配合 unwatch,或 Vue 3 watchEffect 的 onCleanup。

Vue 可选链 & 空值合并配置

Babel 7.15+ + @babel/preset-env 已默认支持 ?.??,无需额外插件。仅旧版 Babel 需单独配置:

  • @babel/plugin-proposal-optional-chaining(?.)
  • @babel/plugin-proposal-nullish-coalescing-operator(??)

Released under the MIT License.