🔥 (224) Looping Over a Range in Vue, Dynamic Returns, and Callbacks

​ ​

Read this on my blog

Hey!

I recently got an email from Ritvik.

He was so inspired by my free "Reactivity From Scratch" mini course that he decided to give this awesome talk on how reactivity works in Vue.

So go watch it and leave some nice comments!

Building Reactivity | Ritvik Sardana

If you're interested in what inspired Ritvik so much, here are some more details on my free "Reactivity From Scratch" mini-course.

We build a Composition API-inspired reactivity system from the ground up.

In it, you will learn to build:

  • ref
  • reactive
  • computed
  • watchEffect
  • readonly
  • isRef
  • unref
  • toRefs
  • shallowRef

By the end you'll have deep knowledge on:

  • Proxy-based reactivity
  • Effect scheduling and cleanup
  • ...and more!

It's structured as a 7-day email course, so it's easy to keep up with a hectic schedule:

  • Day 1: Build a basic reactivity system inspired by Vue 2, including ref() and dependency tracking
  • Day 2: Implement reactive() using Vue 3's powerful proxy-based system for deep reactivity
  • Day 3: Create watchEffect() with advanced features like scheduling, cleanup, and manual stopping
  • Day 4: Develop computed refs for creating derived reactive values
  • Day 5: Master ref manipulation with isRef(), unref(), and toRefs()
  • Day 6: Implement readonly and shallow reactivity for fine-grained control
  • Day 7: Build a reactive store, combining all concepts into a powerful state management solution

Oh, and did I mention that this course is completely FREE?

Whether you're a beginner or an expert at Vue, you'll learn something valuable in this course.

You can ​sign up for it here​.

— Michael

🔥 Looping Over a Range in Vue

The v-for directive allows us to loop over an Array, but it also let's us loop over a range:

<template>    <ul>      <li v-for="n in 5">Item #3</li>    </ul>  </template>

This will render out:

  • Item #1
  • Item #2
  • Item #3
  • Item #4
  • Item #5

When we use v-for with a range, it will start at 1 and end on the specified number.

🔥 Dynamic Returns

A composable can either return a single value or an object of values. Typically, these values are refs.

But we can also dynamically switch between the two depending on what we want to use the composable for:

// Grab only the single value  const now = useNow()    // Get more granular access to the composable  const {    now,    pause,    resume  } = useNow({ controls: true })

This is great because we may only need a single value most of the time. So why complicate the interface for the main use case?

But by dynamically providing the full object of refs, we allow for more advanced use cases as well. Even if they are rarely used.

Here is how we might implement that:

export default useNow(opts) {    const {      controls = false,    } = opts;      // Do some things in your composable      if (controls) {      return { now, pause, resume };    } else {      return now;    }  }

🔥 Reactivity and Callbacks

Callback is a bit of a dirty word in Vue, but there are great use cases for them.

Consider a scenario where a parent component needs to react to changes in its children's state. You can use a reactive object provided by the parent and injected by the children to keep track of changes.

Here's an example:

// Parent component  const sharedState = reactive({});  provide('sharedState', sharedState);    // Child component  const sharedState = inject('sharedState');

When a child component updates a property of sharedState, Vue's reactivity system ensures that any effects or computed properties that depend on sharedState are automatically re-evaluated.

You can use callbacks to allow child components to register themselves with the parent or to signal the parent to perform an action.

Here's how you might implement a callback with provide and inject:

// Parent component  const registerChild = (child) => { /* ... */ };  provide('registerChild', registerChild);    // Child component  const registerChild = inject('registerChild');  registerChild(/* child details */);

This pattern is powerful for creating complex interactions between components while keeping the logic encapsulated and manageable.

It's especially useful in the Compound Components pattern.

📜 Understanding Environment Variables in Nuxt

Environment variables are a crucial part of any application, and Nuxt makes it easy to manage them.

In this article, we'll go over how to set up and use environment variables in Nuxt.

Check it out here: Understanding Environment Variables in Nuxt

📜 The Vite Ecosystem

Vite has taken web development tooling to a new level.

This article explores all of the different tools Vite uses and interacts with, and shows just how much it affects the web development community.

It's very cool to see a project that started out in Vue-land gain wide adoption like this!

Check it out here: The Vite Ecosystem

💬 Stay in bed

"Sometimes it pays to stay in bed on Monday, rather than spending the rest of the week debugging Monday's code." — Christopher Thompson or Dan Salomon

🧠 Spaced-repetition: Mock Nuxt Components When Testing

The best way to commit something to long-term memory is to periodically review it, gradually increasing the time between reviews 👨‍🔬

Actually remembering these tips is much more useful than just a quick distraction, so here's a tip from a couple weeks ago to jog your memory.

When testing, you'll often need to shallow render a component — mocking out any descendent components to keep your test simpler.

With @nuxt/test-utils you can use the mockComponent utility method to help with that:

import { mockComponent } from '@nuxt/test-utils/runtime';    // Use Options API to configure  mockComponent('MyComponent', {    props: {      value: String    },    setup(props) {  		// ...    },  });    // Or use a separate file to clean things up (and use <script setup>)  mockComponent('MyComponent', () => import('./MyComponent.mock.vue'));    // ...tests

🔗 Want more Vue and Nuxt links?

Michael Hoffman curates a fantastic weekly newsletter with the best Vue and Nuxt links.

Sign up for it here.

p.s. I also have a bunch of products/courses:

Unsubscribe

评论

此博客中的热门博文

Scripting News: Tuesday, August 20, 2024

Scripting News: Sunday, January 5, 2025

《中国共产党军事工作重要文献选编》出版发行