This content originally appeared on DEV Community and was authored by Aurélien Delogu
Since I'm unemployed, I'm working on a side project in Vue 3 / TypeScript, so I keep myself up-to-date in frontend development.
Lastly, even if I've 15 years of full-stack experience, I encountered the contenteditable HTML attribute that I didn't know anything about (man there's so much to know in HTML/CSS today).
For those who don't know about it neither, it's an attribute that makes the target tag editable by a simple click: everything is handled natively by the browser itself!
In my application, I had a title that I needed to make editable and I implemented the behaviour by replacing the title by an input when it was clicked. Then I put a v-model attribute on it, and hid the input when the enter button is pressed (and then displayed the title again in place). I already thought when I coded this that it was a bit cumbersome... So I was really intrigued when I met this contenteditable UFO (well, it's not flying per say, but you understood).
I managed to quickly update my code and tested how the thingy worked.
<script setup lang="ts">
import { ref } from 'vue'
const title = ref('My title')
const titleElement = ref(null)
function validate(event : Event) {
(event.target as HTMLInputElement).blur()
title.value = titleElement.value.innerText.trim()
}
defineExpose({ titleElement })
</script>
<template>
<div ref="titleElement" contenteditable spellcheck="false" @keydown.enter="validate">
{{ title }}
</div>
</template>
Well... It seems that is all we need 😅🦄
It's clearly better now without the complexity of dealing the edition by ourselves!
Here's the playable snippet if you want to have fun with it!
If you have any questions, don't hesitate to ask them in the comment section 😉
Photo by Thought Catalog on Unsplash
This content originally appeared on DEV Community and was authored by Aurélien Delogu
Aurélien Delogu | Sciencx (2022-07-11T14:55:57+00:00) How to use the contenteditable attribute in Vue 3. Retrieved from https://www.scien.cx/2022/07/11/how-to-use-the-contenteditable-attribute-in-vue-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.