Vue 2 raw HTML bind to textarea
12,449
Typically you would use v-html
, but you are correct, inside <textarea>
the value will be raw, not processed (will not be bold).
To achieve what you want, maybe you could leverage the contenteditable
property to create a <html-textarea>
, as below.
Vue.component('html-textarea',{
template:'<div contenteditable="true" @input="updateHTML"></div>',
props:['value'],
mounted: function () {
this.$el.innerHTML = this.value;
},
methods: {
updateHTML: function(e) {
this.$emit('input', e.target.innerHTML);
}
}
});
new Vue({
el: '#app',
data: {
message: 'H<b>ELLO</b> <i>editable</i> Vue.js!'
}
});
div[contenteditable] { border: 1px solid lightblue; }
<script src="https://unpkg.com/vue"></script>
<div id="app">
<html-textarea v-model="message"></html-textarea>
<hr>
<div>
Raw message:
<pre>{{ message }}</pre>
</div>
</div>
Related videos on Youtube
Author by
now_world
Updated on June 04, 2022Comments
-
now_world over 1 year
I'm creating an online text editor. I need to be able to get the users text from the textarea's tag, manipulate this text and bind it back to the textarea, but with HTML in it.
Example:
<textarea v-model="someText"></textarea>
Where
someText
is set to:someText: '<b>bold</b>.. not bold'
and should display like: bold.. not bold
instead of:
<b>bold</b>.. not bold
I have a feeling this isn't possible with the
textarea
tag, but what would be a way to do this?-
acdcjunior over 5 yearsTypically you would use
v-html
, but you are correct, inside<textarea>
it will not matter (will not be bold). -
Admin over 5 yearsWhy don't you use the style section of your component to bold the text.
-
now_world over 5 years@altoin How? If I added a span tag and an ID the textarea would just display it.
-
-
now_world over 5 yearsRight, but this bolds all the text inside textarea, not just parts of it.
-
Admin over 5 yearsErrm, yes, i'm not sure you can bold part of the text in a textarea, i think you'd need to use something like ckeditor to achieve that..
-
now_world over 5 yearsWhen I go to update the
message
's datathis.message='<span id="foo">bar</span>
I can see in the Vue devtool's console that themessage
is now updated, but the actual text and html does not display in thehtml-textarea
tag. Any seggestions on how to fix this? -
acdcjunior over 5 yearsYou mean you are updating the
message
from the parent after the initial creation? -
now_world over 5 yearsYes. However, I got the questions answered here.
-
webprogrammer almost 4 years@acdcjunior, I see you have experience with vue and
contenteditable
. Do you know how to insert components intocontenteditable
, store content fromcontenteditable
to database and restore it later for editing? I mean functionality of simple wysiwyg with 'image' button which could insert"some text <simple-image :src="/images/my-image.png" />"
.