Skip to content

Instantly share code, notes, and snippets.

@ashx3s
Last active November 22, 2021 05:36
Show Gist options
  • Select an option

  • Save ashx3s/b76a2f92cff897e0edbb60de59b58dec to your computer and use it in GitHub Desktop.

Select an option

Save ashx3s/b76a2f92cff897e0edbb60de59b58dec to your computer and use it in GitHub Desktop.
Vue v-if

Vue Conditionals

Conditional rendering is really easy in vue

  • use v-if/v-else-if/v-else for content rendering conditionals
  • use v-show for display and css rendering conditionals

v-if/v-else

  • This example will change a message based on a specific value in the data function
  • Template Tag
<div v-if="users[1].likes > users[0].likes">
  <p>People like Sam better than Frodo</p>
</div>
<div v-else-if="users[1].likes < users[0].likes">
  <p>People like Frodo better than Sam</p>
</>
<div v-else="users[1].likes === users[0].likes>
  <p>Frodo and Sam are equally popular amongst the masses</p>
</div>
  • Script Tag
data() {
  return {
    users: [
      {
      name: 'Frodo Baggins',
      likes: 100
    },
    {
      name: 'Samwise Gamgee',
      likes: 500
    }
    ]
  }
}
  • While this example is very simple, using v-on and computed properties, and node packages such as @nuxt/dayjs, you can do very dynamic rendering

v-show

  • v-show is great for making things invisible
  • it sets display: none when the statement is false
  • This example is using the same script content as the v-if/v-else example
  • Template Tag
<div v-show="users[0].likes > users[1].likes">
<p>This will return false and not be visible</p>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment