Skip to main content

Day 15 - Loops, Conditionals, Events

List Rendering and v-for

Activity: Render an Array using a v-for

  • Create an array of strings in your script tags of HomeView
  • Create a ul and put a v-for on an li inside of it
  • Follow the abovenoted documentation for syntax
  • Render the strings in a list

Conditional Directives

  • Conditional Rendering
  • v-if,v-else, and v-else-if: Render content conditionally. This will remove and add content in the DOM.
  • v-show: This will make content visible and invisible by setting the display to none or block (use for things that get toggled a lot). it’s a lighter visibility switch than v-if/else. tutorial that compares v-if to v-show

Use Cases

  • to display content conditionally
  • show the user specific info depending on the situation
  • error handling
  • accomodating variations in layout

Activity: Set content to show conditionally

  • Set a boolean value in the script
  • use v-if and v-else to make the content disappear and reappear

Event Directive

  • v-on for handling events and functions (use this for things like your hamburger menu)

Event Handling

  • Documentation
  • v-on gist with notes on how to use v-on
  • v-on is used to listen to DOM events and trigger a javascript handler (often a function)
  • syntax: v-on:click="handler"
    • or shortened as@click="handler
  • Use this for any buttons on a page
    • set the handler to be a function
  • This can be used with the ref() to make variables more reactive

Event Modifiers

  • To stop a form from being submitted when using a <button>, or to stop other default behaviour, use .prevent
    • @click.prevent="myFunction
    • Check out the other event modifiers
      • @click.once - will only trigger once
      • @click.passive - great for touch events
    • Key modifiers allow for effecting how an event handler is triggered
    • You can specify specific keys using key aliases and key modifiers

Creating Switches

  • To make reactive switches, you’ll want to use the following syntax
  • let variable = reactive({val: false})
    • this will make a reactive variable that response to v-on well
  • const variableSwitch = () => variable.val = !variable.val
    • this will create a switch that changes the variable to false
  • <button @click.prevent="variableSwitch">Click me</button>
    • note that this doesn’t need to be a button

Activity: Make a toggle

  • Create a toggle for the v-if that we made in the last activity
  • Add a @click.prevent directive to a button
  • Make the event switch the boolean variable between true and false
    • variable = !variable
  • See your content change!

Lab Time

  • Work on your assignment
  • Practice using vue directives to render content
  • Look at an old project and map out how you would organize the code into components and pages (pen and paper or whatever medium works)