全局注册自定义指令
// 时间选择器 - 多种输入格式 Vue.directive('dateFormat', { inserted: function (el, binding, vnode) { const { value: _obj } = binding const { context: that, data } = vnode const { expression: key } = data.model if(that && that._isVue) { const $this = $($(el).children('input')[0]) $this.on('change', function() { let value = $this.val() value = value.replace(/^(\d{4})\D*(\d{1,2})\D*(\d{1,2})\D*/, '$1-$2-$3') // 格式化输入格式 const time = value && value.constructor == String ? new Date(value) : value // 转换时间格式 let keys = key.split('.') // 自定义赋值 if (_obj) { const { keys: keyList } = _obj keys = keyList } if (keys && keys.length >= 2) { const [key1, key2, key3, key4] = keys if (key4) { that[key1][key2][key3][key4] = time } else if (key3) { that[key1][key2][key3] = time } else { that[key1][key2] = time } } else { that[key] = time } }) } } })
用法:v-date-format
<el-date-picker
v-date-format
v-model="form.applicantBirthday"
type="date"
placeholder="请选择日期时间"
format="yyyy年MM月dd日"
value-format="yyyy-MM-dd" :picker-options="pickerOptions"
>
</el-date-picker>
自定义赋值
<el-date-picker v-date-format="{ keys: ['additionalInfo', 'otherInfo', i, 'infoValue'] }" format="yyyy年MM月dd日" v-model="p.infoValue" type="date" placeholder="选择日期时间" @change="translateTimes(p,i)"
> </el-date-picker>