I'm trying to do an editable component with Vue 2. It supposed to use the contenteditable attribute in any tag, replacing a normal input. I want to give it a placeholder functionality in order to show a value when none is provided by the user, but I can't seem to get it working.
I'm watching the current value of the component and setting data.isEmpty to true when no user content is present. The component should then show the placeholder value, but currently it shows nothing.
If I console.log the result of the render method, it will show the placeholder child node was instantiated correctly, but for some reason it just won't show on the final HTML.
Here's a JSFiddle: https://jsfiddle.net/dy27fa8t/
And an embedded snippet for those who prefer it:
Vue.component('editable-content', {
props: {
initial: {
type: String
},
placeholder: {
type: String,
required: false
}
},
data() {
return {
value: this.initial,
isEmpty: this.initial === ''
}
},
render: function(createElement) {
const self = this
return createElement(
'div', {
attrs: {
contenteditable: true
},
on: {
input: function(event) {
self.value = event.target.innerHTML
self.$emit('edited', event.target.value)
}
}
},
this.isEmpty ? this.placeholder : this.value
)
},
watch: {
value(to, from) {
this.isEmpty = to === ''
}
}
})
new Vue({
el: '#app',
components: [
'editable-content'
]
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
<div id="app">
<editable-content initial="Initial value" placeholder="Placeholder" />
</div>
initialattribute bound on the component?input, so when no value is set the placeholder shows up.keyon each render, it will set the placeholder, but you lose focus on the DOM element.