Creating a Read More Read Less Button in VueJS

Often on the internet, you might come across a text which is truncated after a certain character and to Read More you will have to press the Read More Button. This is often done for the uniform presentation across all the texts present on the page.

In this tutorial let’s learn how we can achieve the ‘Read more’ and ‘Read less’ button actions in VueJS.


<p>
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum iste <span class="dots">...</span>
    <span class="more">iusto magni voluptas impedit vitae neque aut eaque repudiandae laboriosam in, 
    minima totam animi sunt aliquam? Architecto at esse labore?</span>
</p>

We have a gibberish lorem ipsum text in this example, after a certain number of character we have a span with the class of dots, and after that, we have some more text in the span element with a class of more.
By default, we want to show the dots after the text, and we don’t want to show the text after that.

Let’s define a variable in our Vue Instance and use the v-show directive to achieve the default behavior.


...
<p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum iste <span class="dots" v-show="!more">...</span>
        <span class="more" v-show="more">iusto magni voluptas impedit vitae neque aut eaque repudiandae laboriosam in, minima totam animi sunt aliquam? Architecto at esse labore?</span><br/>
</p>
<a href="#" class="btn btn-primary my-3">Show More</a>
...
...

var app = new Vue({
    el: '#app',
    data: {
        more: false,
    }
    ...
});

Show More VueJs

We have also included a button ‘Show More’ just next to the paragraph.

Next, Let’s add a new method so that on clicking the button we toggle the more variable to true if it’s false and vice versa.


...
{{buttonText}}

...

methods:{
    toggleText: function(){
        this.more = !this.more
    }
},
computed: {
    buttonText: function () {
        return this.more ? 'Show Less' : 'Show More';
    }
}

We have also included a computed Property named buttonText, which changes the text of button to ‘Show More’ or ‘Show Less’ depending on the value of property more.

Demo

Lorem ipsum dolor sit amet consectetur adipisicing elit. Nostrum iste ... iusto magni voluptas impedit vitae neque aut eaque repudiandae laboriosam in, minima totam animi sunt aliquam? Architecto at esse labore?

{{linkText}}

Related Articles

Join my VueJS Newsletter

As I advance in my Journey of learning VueJS, I will be working on different exercises and challenges. Subscribe to receive the latest tutorials (every week) directly in your inbox.

    I won't send you spam. Unsubscribe at any time.

    Powered By ConvertKit

    Site Footer