如何使用bootstrap-vue的BFormTimePicker仅设置分钟和秒?
解决方案
b-form-timepicker的format属性仅控制组件界面的时间展示格式,不会修改v-model绑定值的输出结构,该组件默认输出的时间值包含小时部分,所以仅设置format="mm:ss"无法直接得到你需要的分钟+秒格式数据。
实现步骤
- 第一步:调整组件属性,隐藏小时选择项,避免用户操作小时字段影响最终结果
修改组件代码如下:
<b-form-timepicker id="testDuration" v-model="testDuration" placeholder="Test duration" label-no-time-selected="Set a valid time" label-close-button="Fechar" format="mm:ss" :show-hours="false" />
添加:show-hours="false"后,组件界面只会展示分钟、秒的选择面板,符合你的使用场景。
- 第二步:转换时间值为mm:ss格式提交给API
你可以选择以下任意一种方式处理值转换:
方式1:提交接口前手动转换
// 在接口请求逻辑中加入这段转换代码 if (this.testDuration) { const minutes = String(this.testDuration.getMinutes()).padStart(2, '0') const seconds = String(this.testDuration.getSeconds()).padStart(2, '0') // 提交给API的参数值 const submitDuration = `${minutes}:${seconds}` }
方式2:通过计算属性双向绑定,直接获取mm:ss格式值
如果需要频繁使用该格式的值,可以封装成双向绑定的计算属性:
export default { data() { return { testDuration: null } }, computed: { formattedDuration: { get() { if (!this.testDuration) return '' const m = String(this.testDuration.getMinutes()).padStart(2, '0') const s = String(this.testDuration.getSeconds()).padStart(2, '0') return `${m}:${s}` }, set(val) { // 支持回显接口返回的mm:ss格式时间 if (!val) { this.testDuration = null return } const [minutes, seconds] = val.split(':').map(Number) const time = new Date() time.setHours(0, minutes, seconds, 0) this.testDuration = time } } } }
后续需要使用值的时候直接调用this.formattedDuration即可得到符合要求的格式。
内容的提问来源于stack exchange,提问作者The Apprentice
相关产品推荐
相关产品推荐

