A small Vue.js app
Separating multiline content into <div>
s for display
My Vue.js app uses an element with its contenteditable
attribute set to "true"
to take text input, and to display text stored in the app’s data
element. When content is entered into the element, “paragraphs” (things with line breaks between them) get wrapped in <div>
tags by Firefox and Chrome (though not, as of this writing, by my Safari installation). I have been using CSS to put vertical space between the <div>
s so that they feel like paragraphs.
The app isn’t storing all that HTML, though; it stores the element’s innerText
. When the element’s contents are set from the stored value, line breaks are preserved, but the <div>
tags are not, and so there is no vertical space between paragraphs.
Goal
My aim for this post is to put <div>
tags around paragraphs loaded into the text-tiddler
contenteditable
element from a stored value, so that they can be spaced vertically using CSS.
Reconstituting the <div>
elements
The innerText
property preserves the separation between paragraphs entered into it, via line feeds (\n
). I’ll use the split
method to break up the text into an array of strings separated by \n
characters, then loop through these, creating a string with <div>
tags around each paragraph:
getParagraphs(text) {
var chunks = text.split("\n")
console.log(chunks[0])
var paras = ""
for (var i = 0 ; i < chunks.length ; i++) {
paras += "<div>" + chunks[i] + "</div>"
}
return paras
},
Then it’s a matter of invoking this method to populate the innerHTML
of text-tiddler
, using the v-html
Vue directive in the template:
<div id="text-tiddler" contenteditable="true" v-html="getParagraphs(currentTiddler.text)" @blur="updateTiddlerText"></div>
Now separate paragraphs, retrieved from a data
property (currentTiddler.text
), are placed in separate <div>
s for styling when displayed in the text-tiddler
element.
Current code: minapp_v19.js