🔥 (245) A better way to handle errors (and warnings), mixing local and global styles together, and more

Read this on my blog

What's up?

This week I have a 35% discount on all of the courses I sell on michaelnthiessen.com!

Just use the code BLACKFRIDAY25 at checkout to get the discount. The discount will be available until November 28.

Here's a list of what you can get:

And as always, here are some tips and other Vue content for you.

— Michael

🔥 A better way to handle errors (and warnings)

You can provide a custom handler for errors and warnings in Vue:

// Vue 3  const app = createApp(App);  app.config.errorHandler = (err) => {    alert(err);  };    // Vue 2  Vue.config.errorHandler = (err) => {    alert(err);  };

Bug tracking services like Bugsnag and Rollbar hook into these handlers to log errors, but you can also use them to handle errors more gracefully for a better UX.

For example, instead of the application crashing if an error is unhandled, you can show a full-page error screen and get the user to refresh or try something else.

The warning handler in both versions only works in development.

I created a demo showing how this works. It uses Vue 3, but as seen above, it works nearly the same in Vue 2:

Error Handler Demo

🔥 Mixing local and global styles together

Normally, when working with styles we want them to be scoped to a single component:

<style scoped>    .component {      background: green;    }  </style>

In a pinch though, you can also add a non-scoped style block to add in global styles if you need it:

<style>    /* Applied globally */    .component p {      margin-bottom: 16px;    }  </style>    <style scoped>    /* Scoped to this specific component */    .component {      background: green;    }  </style>

Be careful, though — global styles are dangerous and hard to track down. Sometimes, though, they're the perfect escape hatch and precisely what you need.

🔥 From Options to Composition — The Easy Way

You can use reactive to make the switch from the Options API a little easier:

// Options API  export default {    data() {      username: 'Michael',      access: 'superuser',      favouriteColour: 'blue',    },  	methods: {      updateUsername(username) {        this.username = username;      },    }  };

We can get this working using the Composition API by copying and pasting everything over using reactive:

// Composition API  setup() {    // Copy from data()    const state = reactive({      username: 'Michael',      access: 'superuser',      favouriteColour: 'blue',    });      // Copy from methods    updateUsername(username) {      state.username = username;    }    	// Use toRefs so we can access values directly  	return {      updateUsername,      ...toRefs(state),    }  }

We also need to make sure we change thisstate when accessing reactive values, and remove it entirely if we need to access updateUsername.

Now that it's working, it's much easier to continue refactoring using ref if you want to — or just stick with reactive.

📜 Configuration in Nuxt: runtimeConfig vs. appConfig

Nuxt provides powerful configuration options, allowing you to adapt your application to different use cases.

The two key parts of Nuxt's configuration system are runtimeConfig and appConfig.

This article will explain the purpose and differences between these two options and show you how to use them.

Check it out here: Configuration in Nuxt: runtimeConfig vs. appConfig

📜 Controlling When Components Are Loaded in Nuxt

Nuxt gives us a few different options for controlling when components are loaded.

In this article I explore the different options and how to use each.

Check it out here: Controlling When Components Are Loaded in Nuxt

💬 Write Code for Humans

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." — Martin Fowler

🧠 Spaced-repetition: Forcing a Component to Update

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.

What do you do if a component isn't updating the way it should?

Likely, this is caused by a misunderstanding and misuse of the reactivity system.

But let's look at a quick solution using forceUpdate:

import { getCurrentInstance } from 'vue';    const methodThatForcesUpdate = () => {    // ...    const instance = getCurrentInstance();    instance.proxy.forceUpdate();    // ...  };

Using the Options API instead:

export default {    methods: {      methodThatForcesUpdate() {        // ...        this.$forceUpdate();  // Notice we have to use a $ here        // ...      }    }  }

Now, here comes the sledgehammer if the previous approach doesn't work.

I do not recommend using this approach. However, sometimes you just need to get your code to work so you can ship and move on.

But please, if you do this, keep in mind this is almost always the wrong way, and you're adding tech debt in to your project.

We can update a componentKey in order to force Vue to destroy and re-render a component:

<template>    <MyComponent :key="componentKey" />  </template>    <script setup>  import { ref } from 'vue';  const componentKey = ref(0);    const forceRerender = () => {    componentKey.value += 1;  };  </script>

The process is similar with the Options API:

export default {    data() {      return {        componentKey: 0,      };    },    methods: {      forceRerender() {        this.componentKey += 1;      }    }  }

You can find a deeper explanation here: https://michaelnthiessen.com/force-re-render/

🔗 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

评论

此博客中的热门博文

The magic of scoped slots in Vue ✨ (3/4)

🔥 (#166) Design Patterns and Proxies