|   Read this on my blog Hey all! Not a lot new from me this week, but I've got some JS and Vue tips for you, like always. Enjoy your week! — Michael Nuxt Tips CollectionMaster Nuxt without hours digging through docs. Learn what you need in just 5 minutes a day:         117 practical tips to unlock hidden features of Nuxt  14 chapters covering components, routing, SSR, testing and more  3 daily tips for 3 months via email  7 real-world code repos to learn from  Reviewed by Nuxt core team for accuracy       "Highly recommend Michael's Nuxt Tips Collection. He's one of the best Vue & Nuxt teachers I know." — Sébastien Chopin     Master Nuxt Today → 🔥 Proxy BasicsProxies are one of the strangest but most interesting parts of Javascript. It's a fancy wrapper that lets us create lightweight reactivity systems like in Vue, and so much more. Defining a proxy is simple. We just need to create a handler object, and then use it on an object: const handler = {    get(target, prop, receiver) {      return 'proxied!';    },  };    const someObj = {    hello: 'world',  };    const proxy = new Proxy(someObj, handler);    console.log(proxy.hello) // proxied!
 It lets us intercept property accesses with the get "trap", so we could force any object to use our own logging method:const handler = {    get(target, prop, receiver) {      return () => {        if (typeof target[prop] !== "function") return;          // Force the method to use our own logging method        const consoleLog = console.log;        console.log = (msg) => {          consoleLog(`[${prop}] ${msg}`);        };          target[prop]();          console.log = consoleLog;      };    },  };    const someObj = {    hello() {      console.log('world');    }  }    const proxy = new Proxy(someObj, handler);    proxy.hello() // [hello] world
   We can also intercept when a property is set, prototypes are accessed, and many more things. You can find a complete list on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy 🔥 Simplify Styling with Default Slot WrappersWhen using slots in Vue, you might want to apply default styling to ensure consistent appearance across uses. Instead of requiring slot content to be wrapped every time, you can include the styling wrapper within the slot's component: <!-- StyledSlot.vue -->  <template>    <div class="default-styles">      <slot />    </div>  </template>
 Now, when you use the StyledSlotcomponent, the default styles are automatically applied without extra markup:<template>    <StyledSlot>      Slot content with default styling    </StyledSlot>  </template>
   It's a simple thing, but it makes a difference across a whole app. Be mindful of the type of slot you're creating—layout slots should not include styling, while content slots should. This practice prevents unnecessary CSS from complicating your layout and ensures a clean, consistent look for your components' content. 🔥 Fine-grained Loading API in NuxtIn Nuxt we can get detailed information on how our page is loading with the useLoadingIndicatorcomposable: const {    progress,    isLoading,  } = useLoadingIndicator();    console.log(`Loaded ${progress.value}%`); // 34%
   It's used internally by the component, and can be triggered through thepage:loading:startandpage:loading:endhooks (if you're writing a plugin). But we have lots of control over how the loading indicator operates: const {    progress,    isLoading,    start,      // Start from 0    set,        // Overwrite progress    finish,     // Finish and cleanup    clear       // Clean up all timers and reset  } = useLoadingIndicator({    duration: 1000,  // Defaults to 2000    throttle: 300,   // Defaults to 200  });
   We're able to specifically set the duration, which is needed so we can calculate theprogressas a percentage. Thethrottlevalue controls how quickly theprogressvalue will update — useful if you have lots of interactions that you want to smooth out. The difference between finishandclearis important. Whileclearresets all internal timers, it doesn't reset any values. The finishmethod is needed for that, and makes for more graceful UX. It sets theprogressto100,isLoadingtotrue, and then waits half a second (500ms). After that, it will reset all values back to their initial state. 📜 The Difference Between a Post Flush Watcher and nextTick in VueBoth are used to wait for the DOM to update, but they do it in different ways. We'll explore the differences between them and what it all means. Check it out here: The Difference Between a Post Flush Watcher and nextTick in Vue 📜 Bulletproof Watchers in VueLearn how to write bulletproof watchers in Vue, when to use onCleanup and onWatcherCleanup, and how to build reusable cleanup helpers. Check it out here: Bulletproof Watchers in Vue 💬 Creating complexity"The purpose of software engineering is to control complexity, not to create it." — Unkown 🧠 Spaced-repetition: Global PropertiesThe 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. It's possible to add global properties to your Vue app in both Vue 2 and Vue 3: // Vue 3  const app = createApp({});  app.config.globalProperties.$myGlobal = 'globalpropertiesftw';    // Vue 2  Vue.prototype.$myGlobal = 'globalpropertiesftw';
   I would recommend prefixing any global properties with a $. This helps prevent naming conflicts with other variables, and it's a standard convention that makes it easy to spot when a value is global. This global property can be accessed directly off of any component when using the Options API: computed: {    getGlobalProperty() {      return this.$myGlobal;    },  },
   Why can't this be used with the composition API? Because the composition API is designed to be context-free and has no access to this. Instead, you can create a simple composable to access your globals: <script setup>  import useGlobals from './useGlobals';  const { $myGlobal } = useGlobals();  </script>
 // useGlobals.js  export default () => ({    $myGlobal: 'globalpropertiesftw',  });
   🔗 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: | 
评论
发表评论