benjaminadon
benjaminadon

Reputation: 153

How to properly use a ternary expression with @click event in Vue.js

I'm showing a list of release versions, but the part I'm stuck on is I want to be able to click the release version and show the job_execs for that version. I'm not sure how to do this other than using a ternary expression and binding it to click event. Anyway, what I'm trying to do is not working because nothing changes when I click the versions.

<template> 
  <td>
    <div v-for="release in release_versions" :key="release">
      <li>
        <span @click="showRelease = showRelease === release.version ? '' : release">
          Release {{ release.version }}
        </span>
        <ul v-if="showRelease === release.version">
          {{ release.job_execs }}
        </ul>
      </li>
    </div>
  </td>
</template>
<script>
export default {
  name: 'LatestBuilds',
  data() {
    return {
      release_versions: [
        { version: '1', job_execs: [] },
        { version: '2', job_execs: [] },
      ],
      showRelease: false,
    }
  },
}
</script>

Important things to note:

Upvotes: 2

Views: 4551

Answers (1)

Aryeh
Aryeh

Reputation: 43

I would recommend you use a Method here, instead of adding this logic inside the @click attr.

To actually output the selected release's job_execs, you'll need another v-for inside the ul.

Something like the following should work:

<template> 
  <td>
    <div v-for="release in release_versions" :key="release">
      <li>
        <span @click="selectRelease(release.version)">
          Release {{ release.version }}
        </span>
        <ul v-if="selectedVersion === release.version">
          <li v-for="job_exec in release.job_execs">
            {{ job_exec }} <!-- use job_exec data if this is an object -->
          </li>
        </ul>
      </li>
    </div>
  </td>
</template>
<script>
export default {
  name: 'LatestBuilds',
  data() {
    return {
      release_versions: [
        { version: '1', job_execs: [] },
        { version: '2', job_execs: [] },
      ],
      selectedVersion: null,
    }
  },
  methods: {
    selectRelease(version) {
      this.selectedVersion = version
    }
  },
}
</script>

Upvotes: 3

Related Questions