Categories
Vue 3

How to Register a Global Component in Vue 3?

Sometimes, we may want to add components to our Vue 3 app that’s available throughout the app.

In this case, global components are suitable for this purpose.

In this article, we’ll look at how to register a global component with Vue 3.

Register a Global Component in Vue 3

To register global components with Vue 3, we can use the app.comnponent method.

For instance, we can write:

main.js

import { createApp } from "vue";
import App from "./App.vue";
import HelloWorld from "./components/HelloWorld.vue";

const app = createApp(App);
app.component("hello-world", HelloWorld);
app.mount("#app");

App.vue

<template>
  <div>
    <hello-world />
  </div>
</template>

<script>
export default {
  name: "App",
};
</script>

components/HelloWorld.vue

<template>
  <div class="hello">hello world</div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
};
</script>

In main.js , we import the HelloWorld component and pass that into the app.component method.

The first argument is the component name.

The 2nd argument is the component itself.

Then in App.vue , we use the component by adding the tag with the given component name.

Then in HelloWorld.vue , we add some content to the template.

The component name only works when we use the kebab-case for the tag name since we defined it with a kebab-case tag name.

We can use the hello-world component in any other component since we registered it globally.

Conclusion

We can register a global component easily with Vue 3’s app.component method.

Categories
Vue 3

Add Infinite Scrolling to a Vue.js 3 App with the Intersection Observer API

Infinite scrolling is something that we’ve to add often into our Vue 3 app.

In this article, we’ll look at how to add infinite scrolling to a Vue 3 app with the Intersection Observer API.

Add Infinite Scrolling with the Intersection Observer API

The Intersection API lets us add infinite scrolling easily in our Vue 3 app.

To do this, we assign a ref to the last element and watch when that element is displayed on the screen.

Then when the array changes, we reassign the ref to the last element that’s added then.

For instance, we can write:

<template>
  <div
    v-for="(a, i) of arr"
    :key="a"
    :ref="i === arr.length - 1 ? 'last' : undefined"
  >
    {{ a }}
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      page: 1,
      arr: Array(30)
        .fill()
        .map((_, i) => i),
      observer: undefined,
    };
  },
  methods: {
    async addObserver() {
      await this.$nextTick();
      const options = {
        root: document,
        rootMargin: "20px",
        threshold: 1,
      };

      const callback = (entries) => {
        if (entries[0].isIntersecting) {
          this.arr = [
            ...this.arr,
            ...Array(30)
              .fill()
              .map((_, i) => i + 30 * (this.page - 1)),
          ];
          this.page++;
        }
      };
      this.observer = new IntersectionObserver(callback, options);
      this.observer.observe(this.$refs.last);
    },
  },
  mounted() {
    this.addObserver();
  },
  watch: {
    arr: {
      deep: true,
      handler() {
        this.addObserver();
      },
    },
  },
};
</script>

We have a series of divs rendered from the arr array in the component template.

The ref prop is set by checking whether the index of the item is the same as arr.length — 1 .

If it is, then it’s the last item, so we assign a ref to that.

Otherwise, we don’t assign a ref to it.

The data method returns the page number and the arr array with the data to render.

In the methods object, we have the addObserver methgod to add the Intersection Observer and use that to watch when the element that we assigned the ref to appears on the screen.

To do this, we call $nextTick to make sure the elements are rendered.

Then we set the options for detecting intersection.

root is the element that has the items we watch for.

rootMargin is the margin to determine when the item is considered to be on the screen.

threshold is the threshold for the element to be displayed. It’s the portion of the element that’s appeared on the screen. And it’s a number between 0 and 1.

Next, we have the callback function that checks the isIntersecting property to see if the last element appeared.

If it has, then we update the arr array by putting more entries in it.

We also update the page value.

Next, we create the IntersectionObserver instance with the callback and options .

Then we call observe on it with the element that’s been assigned the ref to watch it appear on the screen.

We call this method with the component is mounted and when the arr array changes.

The mounted hook runs after the component is rendered, so we can get the element with the ref assigned and watch it appear on the screen.

Now when we scroll down, we should see more items appear.

Conclusion

We can use the Intersection Observer API easily to add infinite scrolling easily into our Vue 3 app.

Categories
JavaScript Answers

How to Get a CSS Property Value of an Element with JavaScript?

Sometimes, we may want to get a CSS property value of an element with JavaScript.

In this article, we’ll look at how to get a CSS property value of an element with JavaScript.

Use the window.getComputedStyle Method

We can use the window,getComputedStyle method to get the computed CSS styles of an element.

For instance, if we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = window.getComputedStyle(div);
const height = style.getPropertyValue('height');
console.log(height)

to add some content to the div.

We have the for loop to add 100 p elements into the div with document.createElement .

Then we set the textContent of each element to add some content.

And then we call div.appendChild to add the p elements as children of the div.

Next, we call window.getComputedStyle with the div to get a style object.

And then we can get the height property with:

const height = style.getPropertyValue('height');

And height is '300px' since we set it as such in the HTML.

Use the Element’s computedStyleMap Method

Also, we can use the computedStyleMap method that comes with elements to get the styles applied to the element.

For instance, we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

And we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = div.computedStyleMap();
const height = style.get('height');
console.log(height)

Everything above the last 3 lines is the same as before.

Then we call div.computedStyleMap to get a style object that we can use to get the styles.

And then we have:

const height = style.get('height');

to get the CSSheight property value of the div.

This time height should be:

{value: 300, unit: "px"}

The value and unit are separate properties in the returned object.

Conclusion

There’re a few ways we can use to get the CSS properties from an element with JavaScript.

Categories
JavaScript Answers

How to Get the Scrollbar Position with JavaScript?

Sometimes, we may want to get the position of the scrollbar when we’re scrolling on an element or page.

In this article, we’ll look at how to get the scrollbar position with JavaScript.

Using the scrollTop Property of an Element

We can use the scrollTop property of an element to let us get the number of pixels hidden because of scrolling.

So we can use this to get the position of the scrollbar.

For instance, we can write the following HTML:

<div>

</div>

Then we can listen to the scroll event by writing:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

window.addEventListener('scroll', (e) => {
  console.log(document.documentElement.scrollTop);
})

We get the div with the document.querySelector method.

Then we add 100 p elements into the div by calling document.createElement to create the elements.

And we set the content of each by setting the textContent property.

Then we append it to the div with the div.appendChild method.

Next, we call window.addEventListener with the 'scroll' string as the first argument to listen to the scroll event.

And then we can get the scrollTop property of the documentElement to get how far the html element has scrolled down.

We can also get the scrollTop property of other elements.

For instance, if we have:

<div style='height: 300px; overflow-y: auto'>

</div>

We set the height and overflow-y properties to make the div scrollable.

Then we can listen to the scroll event of the div by writing:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

div.addEventListener('scroll', (e) => {
  console.log(div.scrollTop);
})

We add the content to the div like we have before.

But we call div.addEventListener instead of window.addEventListener to listen to the scroll event of the div.

Then we get the div.scrollTop property to get how far the div has scrolled down.

Using the scrollY Property of the window Object

There’s also the window.scrollY property to let us get how far down the scrollbar is in pixels.

For instance, we can use it by writing:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

window.addEventListener('scroll', (e) => {
  console.log(window.scrollY);
})

We still listen to the 'scroll' event, but we get the window.scrollY property instead of document.documentElement.scrollTop .

Conclusion

There’re several ways we can use to get the scrollbar position with JavaScript.

Categories
JavaScript Answers

How to Convert a String of Numbers to an Array of Numbers in JavaScript?

Sometimes, we have a string with a comma-separated list of numbers that we want to convert to an array of numbers.

In this article, we’ll look at how to convert a string of numbers to an array of numbers in JavaScript.

Using String and Array Methods

We can use the split method available with JavaScript strings to convert a string into an array of strings by splitting the string by a separator.

So we can use the split method to split the string into an array of strings by the commas.

So it’ll return an array of strings with the stuff between the commas.

Then we can call the array map method to map the split string array entries into numbers.

For instance, we can write:

const nums = "1,2,3,4".split(`,`).map(x => +x)
console.log(nums)

We call split with the comma to separate the string into an array with the number strings in it.

Then we call map with a callback that converts each entry to a number with the unary + operator.

Therefore, nums is [1, 2, 3, 4] as a result.

Instead of using the unary + operator, we can also use the parseInt function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseInt(x, 10))
console.log(nums)

parseInt takes 2 arguments.

The first argument is the value we want to convert to a number.

The 2nd argument is the base that we want the returned number to be in.

So 10 would convert x to a decimal number.

Therefore, we get the same result as before.

Another way to convert the strings to numbers is to use the Number function.

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => Number(x))
console.log(nums)

and we get the same thing.

Number always convert to decimal numbers so we don’t have to specify it.

There’s also the parseFloat function that converts a value to a floating-point number if we want to do that.

It takes the same argument as parseInt .

To use it, we write:

const nums = "1,2,3,4".split(`,`).map(x => parseFloat(x, 10))
console.log(nums)

And we get the same result as before for nums .

Conclusion

We can convert a string of numbers to an array of numbers with some string, array and number functions.