-
-
Save laphilosophia/0be56bb1a09dfcb4ac596a7905da0e29 to your computer and use it in GitHub Desktop.
Vue ContentEditable
This file contains 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
export default { | |
name: 'content_editable', | |
template: '<div ref="element" v-html="text"></div>', | |
props: { | |
text: [String], | |
customTag: [String], | |
}, | |
mounted: function() { | |
let newElement = document.createElement(this.customTag || 'div') | |
this.$refs.element.parentNode.replaceChild(newElement, this.$refs.element) | |
this.$refs.element = newElement | |
this.$refs.element.contentEditable = true | |
this.$refs.element.innerHTML = this.text | |
this.$refs.element.addEventListener('DOMSubtreeModified', () => { | |
this.$emit('edit', this.$refs.element.innerText) | |
}) | |
this.$refs.element.addEventListener('blur', () => { | |
this.$emit('blur') | |
}) | |
this.$refs.element.addEventListener('focus', () => { | |
this.$emit('focus') | |
}) | |
}, | |
beforeDestroy: function() { | |
this.$refs.element.parentNode.removeChild(this.$refs.element) | |
}, | |
watch: { | |
text: function() { | |
if (this.text !== this.$refs.element.innerHTML) { | |
this.$refs.element.innerHTML = this.text | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment