Day 20 - Vue Reactivity
Friday Follow Up
- Nuxt Image
- Nuxt Icon
- Deployment to Netlify
Activity: Add Images to a Page
- Documentation
- Add images to
assets/images
and public/images
- Use the Nuxt Module to add the images to your page
- Set using the module’s
sizes
, width
, height
, and format
attributes
- Check on the performance using your devtools
Event Listeners Follow Up
- 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
- See your content change!
Reactive Variables in Vue 3
- Reactivity Fundamentals
- syntax:
ref()
: ‘Takes an inner value and returns a reactive and mutable ref object, which has a single property .value that points to the inner value.’
reactive()
: ‘Returns an active proxy of the object’
- What they do:
- Make vue track changes to the variables and re-evaluate dependent variables etc
- Differences:
- ref() is for strings, numbers, booleans and objects
- reactive() is for objects
- ref() uses
.value
to access the properties
- When to choose each
- for most cases you should use
ref()
reactive()
is great for when you need to use map
- Storage past refresh?
- for longer term storage, you would use a store like pinia
Activity: Create a reactive toggle
- Set a ref() variable up as a Boolean toggle
- Add a v-on event to the page to change the Boolean value
- Use
v-show
with your toggle to hide/show content
Lab Time
- Assignment 4
- Practice Vue Content