Skip to content

VueJS 3 – substr / truncation in template / v-for?

I’m pretty new to VueJS and have an understanding problem i couldn’t find any help for.

Its pretty simple: I’m getting a JSON through an API with axios. This item contains a description that I want to output on the page.

My code looks something like this:

<template>
   <div v-for="item in listitems" :key="item.id">
       {{ item.description }}
   </div>
</template>


<script lang="ts">
import { defineComponent } from 'vue';
import axios from 'axios'

export default defineComponent({
    name: 'AllCoupons',
    components: {
    },
    data: function() {
        return {
            listitems :[] 
        }
    },
    mounted: function() {
        axios.get('https://api.com/endpoint',
        {
            headers: {
                'Accept': 'application/json'
            }
        }).then((response) => {
            console.log(response);
            this.listitems = response.data.data
        }).catch(error => {
            console.log("ERRR:: ", error.response.data)
        });
        
    }
  
});
</script>

It works fine so far. The problem is that the item.description has too many characters, which I’d like to limit with something like substr. What is the right / best way to do something like this in vue?

I thought about adding a custom function in methods which will be run after the api fetched the data to iterate trough the data and make the modifications then, before passing it back to this.listitems. – But is there a way to do something like this in the template: ?

{{ item.description.substring(1, 4); }}


I knew something like this was possible with Vue 2 and filters if I’m right… But how can I do something like this in Vue 3?

Thanks a lot!!

Answer

As suggested in migration guide, you could use a computed property like :

 data: function() {
        return {
            listitems :[] 
        }
    },
computed:{
   customItems(){
     return this.listitems.map(item=>{
        return {...item, description:item.description.substring(1, 4)}
    }
   }
}

then render that computed property :

  <div v-for="item in  customItems" :key="item.id">
       {{ item.description }}
   </div>