Created
June 27, 2018 08:49
-
-
Save underdoeg/ddd3acee8872eb045db799fb1c352440 to your computer and use it in GitHub Desktop.
minimal inline edit vue component
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
<inline-edit :data="your.data" @update="vyour.data = $event" placeholder="Write data..."></inline-edit> |
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 class="editable" contenteditable="true" :placeholder="placeholder" @input="update" @focusin="onFocus" @focusout="checkEmpty"></div> | |
</template> | |
<script> | |
export default { | |
name: "InlineEdit", | |
props: { | |
data: String, | |
placeholder: { | |
default: "write here...", | |
type: String | |
} | |
}, | |
mounted: function () { | |
this.$el.innerText = this.data; | |
}, | |
watch: { | |
data(newData, oldData) { | |
if(document.activeElement !== this.$el) { | |
this.$el.innerText = newData; | |
} | |
} | |
}, | |
methods: { | |
update(event) { | |
this.$emit('update', event.target.innerText); | |
}, | |
onFocus(event){ | |
this.$emit('focus'); | |
}, | |
checkEmpty(event) { | |
if (!this.$el.innerText.trim().length) { | |
this.$el.innerText = ""; | |
} | |
} | |
} | |
} | |
</script> | |
<style scoped> | |
.editable{ | |
min-height: 1em; | |
} | |
.editable[placeholder]:empty:before { | |
content: attr(placeholder); | |
opacity: .8; | |
} | |
.editable[placeholder]:empty:focus:before { | |
content: ""; | |
} | |
</style> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment