Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Truncate words (chars) in vuejs 3

How to truncate words or chars in VueJs 3 ? I searched some answers but didn’t work for me.
For example if description words length more than 200 , it should display 200 words and … at the end

What I tried so far..

<p>{{ announcement.description | truncate(200) }}</p>

<script>
export default {
data() {
    return {
      announcement: {},
    }
  },
computed:{
    truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length) + "...";
        } else {
            return value;
          }
    }
  }
}
</script>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

What you are looking for is a method, not a computed property. A computed property is used to declaratively describe a value that depends on other values. Move your code to methods and pass the argument with the length it should work.

    methods: {
       truncate(value, length) {
        if (value.length > length) {
            return value.substring(0, length) + "...";
        } else {
            return value;
          }
      }
   }

And just call this method from the template:

truncate(announcement.description,200)

You can read about correct usage of computed from here:
https://vuejs.org/v2/guide/computed.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading