Skip to content

🔥 (#62) Detect Clicks Outside of an Element

May 2022

Hey!

I hope you're having a wonderful week!

As always, here are some tips for you.

— Michael

🔥 Detect Clicks Outside an Element

Sometimes I need to detect whether a click happens inside or outside of a particular element. This is the approach I typically use:

window.addEventListener("mousedown", (e) => {
  // Get the element that was clicked
  const clickedEl = e.target;

  // `el` is the element you're detecting clicks outside of
  if (el.contains(clickedEl)) {
    // Clicked inside of `el`
  } else {
    // Clicked outside of `el`
  }
});

🔥 Define multiple components in a single file

Every now and then, you just need a small component, one that's not worth an entirely new file:

// A small, secondary component
const SmallComponent = {
  // Create a component like you normally would
  data() {
    //...
  },
  computedProps: {
    //...
  },

  // Use the template property instead of a template block
  template: `
    <div>Hello!</div>
  `,
};

// Your main component
export default {
  components: { SmallComponent },
  // ...
};

This is perfect for reusing code within a component where a v-for doesn't work.

However, if the code is more complex or is likely to be used by other components, making a proper reusable component is the best way to go.

Note: You can get proper syntax highlighting of the HTML string using this VSCode extension.

📜 Vue vs React —How to Go from One Framework to the Other

A very interesting comparison on how the two frameworks solve different problems. I've written React before, but it's a good refresher on how devs in React-land do common tasks.

Read it here: Vue vs React —How to Go from One Framework to the Other

💬 The First Step

"The first step of any project is to grossly underestimate its complexity and difficulty." —Nicoll Hunt

🧠 Spaced-repetition: Next Tick: Waiting for the DOM 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.

Vue gives us a super handy way for us to wait for the DOM to finish updating:

// Do something that will cause Vue to re-render
changeTheDOM();

// Wait for the re-render to finish
await nextTick();

// Now we can check out the freshly minted DOM
inspectTheDOM();

Or if you're using the options API:

await this.$nextTick();

A tick is a single render cycle. Vue listens for any reactivity changes, then performs several updates to the DOM in one batch. Then the next tick begins.

If you update something in your app that will change what is rendered, you have to wait until the next tick before that change shows up.

p.s. I also have two courses: Reusable Components and Clean Components

来源

原文 https://michaelnthiessen.com/weekly-062-may-25/

本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。