M
M
MaXX777772021-10-04 13:43:34
JSON
MaXX77777, 2021-10-04 13:43:34

Good afternoon! How to access a specific array of objects and its specific property using Axios and Vue js?

<body>
    <div id="app">
        <ul>
            <div v-for="messages in message">{{ messages.name }}</div>

        </ul>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sass.js/0.11.1/sass.min.js"></script>

    <script>
        let app = new Vue({
            el: '#app',
            data: {
                message: ''
            },
            mounted() {
                axios
                    .get('test.json')
                    .then(response => (this.message = response.data));
            }
        })
    </script>

</body>



есть файл test.json


[
    {
        "name": "Vasia",
        "age" : "33"
    },
    {
        "name": "Ulia",
        "age" : "31"
    },

    {
        "name": "Petia",
        "age" : "35"
    },
    {
        "name": "Sergey",
        "age" : "30"
    }
]


I want to reach the 3rd object in the array and display only its name (name) on the page.

Example: Petya

But it displays the entire list of names for me. How to fix it? Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-10-04
@MaXX77777

So you have the same, the entire array is displayed in a loop:

<div v-for="messages in message">{{ messages.name }}</div>

Make it a computed property like:
computed: {
  thirdName() {
    if (this.messages.length >= 3) {
      return this.messages[2].name;
    }
  }
},
and show it when not empty: PS print the whole list:<div v-if="thirdName">Имя: {{ thirdName }}</div>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question