I'm currently working on creating an editable component using Vue 2. I am trying to utilize the contenteditable
attribute within any tag, as a substitute for a regular input field. My goal is to implement a placeholder feature that displays a default value when the user does not provide any content. However, I am encountering difficulty getting this functionality to work.
I have set up the component to monitor its current value and assign true
to data.isEmpty
when there is no user-generated content present. The intention is for the component to display the placeholder value in such cases, but it is currently appearing blank.
Upon inspecting the result of the render
method with a console.log
, it indicates that the placeholder child node has been instantiated correctly. Nevertheless, the placeholder content fails to appear in the final HTML output for some unknown reason.
For reference, here is a link to the JSFiddle containing the code: https://jsfiddle.net/dy27fa8t/
Additionally, here is an embedded code snippet:
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>