Pinia Getters 适合封装日期格式化逻辑:无参 getter 用于固定格式,返回函数的 getter 支持多格式动态切换;必须基于响应式 date 对象,避免副作用;单组件场景优先用 computed。

Pinia Getters 本身不直接处理日期格式化,但它是组织和复用格式化逻辑的理想位置——关键在于把“格式化”作为派生状态来管理,而不是在组件里重复写 moment(date).format('YYYY-MM-DD') 或手动拼接。
用 Getter 封装固定格式的日期显示
当某个日期字段(比如 currentWeekStart)需要统一以「2024年6月17日」形式展示时,适合定义无参 getter:
- 在 store 中声明:
currentWeekStart: ref(moment().startOf('week')) - 对应 getter:
weekLabel: (state) => state.currentWeekStart.format('YYYY年M月D日') + ' - ' + state.currentWeekEnd.format('M月D日') - 组件中解构使用:
const { weekLabel } = storeToRefs(store),模板直接写{{ weekLabel }}
用返回函数的 Getter 实现多格式动态切换
如果同一日期需按不同场景输出(如列表用「YY/MM/DD」、详情页用「MMM DD, YYYY」),Getter 应返回一个接收 format 字符串的函数:
- 写法示例:
formattedDate: (state) => (format = 'YYYY-MM-DD') => state.selectedDate?.format(format) || '' - 调用方式:
store.formattedDate('YYYY年M月D日') 或 store.formattedDate('MM/DD') - 注意:Pinia 不会为不同 format 参数缓存结果,每次调用都实时计算,确保响应式更新
避免在 Getter 中做副作用或依赖非响应式值
日期格式化必须基于 store 中已响应式的 date 对象(如 moment 实例或 Date ref),不能在 getter 内部调用 new Date() 或 Date.now():
- ❌ 错误: nowText: () => moment().format('HH:mm:ss') —— 不响应、不缓存、每次渲染都变
- ✅ 正确:把当前时间也纳入 state 管理,例如 lastRefresh: ref(new Date()),再写 getter:refreshTime: (state) => moment(state.lastRefresh).format('HH:mm:ss')
- 额外提示:moment 对象是可变的,建议在 action 中用
.clone()再格式化,防止污染原始值
结合计算属性做轻量级格式化(不走 Pinia)
如果格式化只用于单个组件内,且参数来自 props 或本地 ref,更推荐在组件内部用 computed 处理:
- 例如:const displayDate = computed(() => dayjs(props.date).format('MM-DD ddd'))
- 这样避免把临时视图逻辑塞进 store,职责更清晰,也省去 getter 缓存管理的复杂度










