Check if an array is empty with Vue.js

Asked

Viewed 936 times

0

I am new to javascript and thought about doing some tests with some tools (the Vue.js and nuxt.js) to learn something new. So taking a test that I was sent (which comes down to doing a job vacancy page) I found an issue that I can’t solve, which would be:

I have a json array of several job vacancies and what your requests for it, but they have some inconsistencies, for example:

    {
    vaga: 'Progamador(a) PHP',
    nome_empresa: 'xxxxxxxxx',
    url_banner: 'https://yyyyyy.com/hhh.png',
    valor: 1500,
    area: 'Desenvolvimento',
    senioridade: 'Pleno',
    tags: [],
    cidade: 'São Paulo',
    id: '1'
  },

As we have above, the value of tags this empty, however it is still an array, which should be so:

    {
    vaga: 'Progamador(a) PHP',
    nome_empresa: 'xxxxxxxxx',
    url_banner: 'https://yyyyyy.com/hhh.png',
    valor: 1500,
    area: 'Desenvolvimento',
    senioridade: 'Pleno',
    tags: ['PHP', 'Laravel', 'MySQL', 'Pleno', 'Bootstrap'],
    cidade: 'São Paulo',
    id: '1'
  },

For me to display this information on the screen...

<div class="modal-body">

    {{ job.nome_empresa }} está contratando {{ job.vaga }} {{ job.senioridade }}, para trabalhar na área de {{ job.area }} <div v-if="">É preferivel skills em:

    <ul>

        <li v-for="(tag, i) in job.tags" :key="i" v-if="tag"> {{ tag }} </li>

    </ul>

  </div>

</div>

That way, I mean, I don’t want to flaunt what’s after the <div v-if="">É preferivel skills em: when no Skill is required...

Thanks in advance, and as I am inciante in this area, if you have any kind of study / video to recommend, I would be very grateful also!

  • Have you tried putting the v-for="(tag, i) in job.tags" in the <ul> ?

  • Yes, it would create a "ul" for each tag within "tags", which would not be what I want, which is to display the tags in a list when you have tags in the variable. And when he has nothing, he displays nothing

2 answers

3


You can make a .length in the array, in case when there is no element, the div.

Thus:

<div v-if="job.tags.length">

1

If you are not sure that "tags" will always exist, I recommend using the following format:

<div v-if="job.tags && jobs.tags.length > 0">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.