K
K
Kneepy2021-10-01 14:01:54
Vue.js
Kneepy, 2021-10-01 14:01:54

Displaying the last element of an array in an array iterated over by v-for?

There is an array element:

{
   /*бла бла*/
    "messages": [{
        /*бла бла*/
        "value": "gwegweg",
       /*бла бла*/
    }, {
        /*бла бла*/
        "value": "ewfwef",
        /*бла бла*/
    }],
    /*бла бла*/
}

And inside this object we need to display the last element of this array, or rather the value property, I tried to do it with something like
elem.messages[elem.messages.length - 1].value
But vue gives an error, while the code above only .valuereads normally without and outputs:
{"value": "ewfwef"}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-10-01
@Aleksandr-JS-Developer

Kneepy , vue has great functionality for such tasks. It is called computed-properties.
You can add this to your component:

export default {
  ...
  computed: {
    lastMessage(){
      return this.messages[messages.length-1]
    }
  }
  ...
}

In the template you will now have a new variablelastMessage
<template>
  ...
  {{ lastMessage.value }}
  ...
</template>

If you need only value, then you can return from computed Then in the templatereturn this.messages[messages.length-1].value
<template>
  ...
  {{ lastMessage }}
  ...
</template>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question