DEV Community

Laur.Rvt
Laur.Rvt

Posted on • Edited on

Read More/Read Less functionality with Vue

Hi!
In this post I am going to show you a simple way to do a Read More/Read Less functionality in vue.js.

One way to do that is to have two divs that will store both versions of the text (the long and the short one) but that is working only if we work with static texts.

This is a working version of that functionality using a variable in which will be stored our text:
https://codesandbox.io/s/eager-kowalevski-u406b?file=/src/App.vue

The idea is pretty simple. I just have a bool variable named "readMore" which will control displaying of Read More and Read Less buttons. Also, using readMore ,I give to div that stores the text a new class named "readLess" which have it own styles.
Hope it was useful for you. If you have any questions or suggestions, feel free to text me about that :)

Top comments (4)

Collapse
 
aarone4 profile image
Aaron Reese

But the text us still in the DOM. If you need to remove it, use a computed function to return a short string or array of short strings and then conditionally return the short or long version using v-if directive or the ternary operator.

Collapse
 
laurrvt profile image
Laur.Rvt

Thanks for sharing that.
The point was to make it really simple and in a better way (in my opinion) that I have found on forums. For example, in this post dev.to/ebenoladutemu/simple-read-m... author shows how to do that for static texts which is not really working for me.
Is that really a problem that text is still in the DOM? I mean it looks good just hiding it, but maybe I don't know something. Tell me please about that :)

Collapse
 
aarone4 profile image
Aaron Reese

Depends on your use case. If text was behind a paywall or was the answer to a quiz or should be suppressed for screen readers then yes, having it in the DOM would be an issue but most of the time probably not.
But that is why you also have v-if and v-show. The latter adds or removes visibility: hidden, the former actually adds or removes the DOM element

Thread Thread
 
laurrvt profile image
Laur.Rvt

Never thought about that but thanks. I will consider your advice :)