Last active
November 25, 2018 05:22
-
-
Save cjcrawford/622701c52b8e4cde41d4ebe70df70f71 to your computer and use it in GitHub Desktop.
DatePicker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<div> | |
<input ref="input" type="text" v-model="localValue" /> | |
<slot :localValue="localValue" :formattedDate="formattedDate"> | |
{{ formattedDate }} | |
</slot> | |
<!-- parent can now use 'render prop through scoped slot' --> | |
<!-- | |
<DatePickerComponent slot-scope="{localValue, formattedDate}" :value="value" @input="handleChildInput" @clear="clearChildInput"> | |
{{ formattedDate }} | |
</DatePickerComponent> | |
--> | |
</div> | |
</template> | |
<script type="text/babel"> | |
require('eonasdan-bootstrap-datetimepicker') | |
export default { | |
name: 'DatePickerComponent', | |
data () { | |
return { | |
localValue: null | |
} | |
}, | |
props: { | |
value: { | |
type: [Date, String, Object] // new Date(), '2018-08-26', moment() | |
} | |
}, | |
mounted () { | |
if (window.dp === undefined) { | |
window.dp = $(this.$refs.input).datetimepicker() | |
.on('dp.change', this.handleChange) | |
} | |
}, | |
destroyed () { | |
// clean up event listener | |
if (window.dp !== undefined) { | |
window.dp.off('dp.change', this.handleChange) | |
} | |
}, | |
methods: { | |
handleChange (event) { | |
// tell parent the user changed data | |
const {date} = event | |
if (!!date) { | |
return this.$emit('input', date) | |
} | |
return this.$emit('clear') | |
} | |
}, | |
computed: { | |
formattedDate () { | |
return !!this.localValue && moment(this.localValue).isValid() | |
? moment(this.localValue).tz('UTC').format('YYYY-MM-DD[T]HH:mm:ssZ') | |
: 'invalid date' | |
} | |
}, | |
watch: { | |
value: (newVal) { | |
handler (newVal) { | |
if (newVal !== this.localValue) { | |
this.localValue = newVal | |
} | |
}, | |
immediate: true | |
} | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment