Sometimes you may want users to be able to edit content or text without having to show an input or text field. This comes useful in situations when some quick changes in text are needed.
HTML provides an attribute called contentEditable to serve the purpose. You can make use of this attribute, and then update the content as needed (edit content on click and change). It’s a bit little tricky though, you don’t want to update the actual content of the original text. By doing that, you’ll be forced to have you cursor moved to the begging of the line after every input. Therefore, you’d need a temporary variable to hold the initial state.
Here in this demo, I’ll show you how to achieve that:
<template>
<div id="app">
<h2 contenteditable @input="updateContent($event, 'heading')">
{{ contentHeadingTemp }}
</h2>
<p contenteditable @input="updateContent($event, 'paragraph')">
{{ contentMessageTemp }}
</p>
</div>
</template>
<script>
const headingText = "Hello from nightprogrammer.com!";
const contentText =
"Feel free to click on the title above or this paragraph, to make changes!";
export default {
data() {
return {
contentHeading: headingText,
contentHeadingTemp: headingText,
contentMessage: contentText,
contentMessageTemp: contentText,
};
},
methods: {
updateContent(e, contentType) {
const inputText = e.target.innerText;
switch (contentType) {
case "heading":
this.contentHeading = inputText;
break;
case "paragraph":
this.contentMessage = inputText;
break;
default:
break;
}
},
},
};
</script>
<style scoped>
#app {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
</style>
Code language: HTML, XML (xml)
In the code above, I’ve stored two strings in two constants (line 13 and 14). I’ve then coped their valued to the initial states of contentHeading through contentMessageTemp (line 20 through 23). As you can see, I’ve shown the initial values of the strings on line 4 and 7. Now with every input, I’ve updated the values in the states contentHeading and contentMessage (line 31 and 34). It means that whenever you input some changes, it won’t be directly shown as text using these states, but from the temporary states. However, the actual states will be saving the input values as you type.
You can find a working copy of the above code from my repos below: