Categories
Vue Answers

How to Listen to the Window Scroll Event in a Vue.js Component with JavaScript?

Sometimes, we want to listen to the window scroll event in a Vue.js component with JavaScript.

In this article, we’ll look at how to listen to the window scroll event in a Vue.js component with JavaScript.

Listen to the Window Scroll Event in a Vue.js Component

We can listen to the window scroll event in a Vue.js component by calling the window.addEventListener method to listen to the scroll event on the browser window.

For instance, we can write:

<template>
  <div id="app">
    <p v-for="n of 100" :key="n">{{ n }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  created() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll(event) {
      console.log(window.scrollY);
    },
  },
};
</script>

We call window.addEventListener with 'scroll' in the created hook to add the handleScroll scroll event listener when the component is mounted.

And in the destroyed hook, we call window.renmoveListener to remove the handleScroll scroll event listener.

In the handleScroll method, we have the window.scrollY property to get the vertical scroll position.

In the template, we have some scrollable content. If we scroll through it, we should see the scrollY value logged.

Conclusion

We can listen to the window scroll event in a Vue.js component by calling the window.addEventListener method to listen to the scroll event on the browser window.

Categories
Vue Answers

How to Scroll to an Element with Vue.js and JavaScript?

Sometimes, we want to scroll to an element with Vue.js and JavaScript.

In this article, we’ll look at how to scroll to an element with Vue.js and JavaScript.

Scroll to an Element with Vue.js and JavaScript

We can scroll to an element with Vue.js by assigning a ref to the element we want to scroll to.

Then we can scroll to the element by calling the scrollIntoView method on the element assigned to the ref.

For instance, we can write:

<template>
  <div id="app">
    <button @click="scrollToElement">scroll to last</button>
    <p v-for="n of 100" :key="n" :ref="n === 100 ? 'last' : undefined">
      {{ n }}
    </p>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    scrollToElement() {
      const [el] = this.$refs.last;
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
};
</script>

We have the scroll to last button that calls scrollToElement .

Then we have some p element with the last ref being assigned to the last p element.

In the scrollToElement method, we get the element assigned to the last ref with this.$refs.last via destructuring.

Then we call el.scrollIntoView with an object that has the behavior property to change the scroll behavior.

Conclusion

We can scroll to an element with Vue.js by assigning a ref to the element we want to scroll to.

Then we can scroll to the element by calling the scrollIntoView method on the element assigned to the ref.

Categories
Vue Answers

How to set data type in Vue.js data object with TypeScript?

Sometimes, we want to set data type in Vue.js data object with TypeScript.

In this article, we’ll look at how to set data type in Vue.js data object with TypeScript.

How to set data type in Vue.js data object with TypeScript?

To set data type in Vue.js data object with TypeScript, we can set the type using as.

For instance, we write

<template>
  <div ref="root">This is a root element</div>
</template>

<script lang="ts">
export default {
  //...
  data() {
    return {
      players: [] as Player[],
    };
  },
  //...
};
</script>

to set the players reactive property to the Player[] type with as Player[].

Conclusion

To set data type in Vue.js data object with TypeScript, we can set the type using as.

Categories
Vue Answers

How to fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript?

Sometimes, we want to fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript.

In this article, we’ll look at how to fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript.

How to fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript?

To fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript, we can use the ref function from the composition API.

For instance, we write

<template>
  <div ref="root">This is a root element</div>
</template>

<script lang="ts">
import { ref, onMounted, defineComponent } from "@vue/composition-api";

export default defineComponent({
  setup() {
    const root = ref(null);

    onMounted(() => {
      console.log(root.value);
    });

    return {
      root,
    };
  },
});
</script>

to call ref to create the root ref.

And then we set the ref prop to root to assign the div to the root ref.

Then we get the div from root.value.

Conclusion

To fix the ‘this.$refs.refField.value does not exist’ error with Vue.js and TypeScript, we can use the ref function from the composition API.

Categories
Vue Answers

How to filter on array with Vue.js?

Sometimes, we want to filter on array with Vue.js.

In this article, we’ll look at how to filter on array with Vue.js.

How to filter on array with Vue.js?

To filter on array with Vue.js, we can return the filtered array in a computed property.

For instance, we write

<template>
  <div>
    <div>
      <input type="text" v-model="search" />
      <label>Search Users:</label>
    </div>
    <ul>
      <li v-for="user in filteredAndSorted" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  //...
  data() {
    return {
      search: "",
      userList: [
        {
          id: 1,
          name: "Prem",
        },
        {
          id: 1,
          name: "Chandu",
        },
        {
          id: 1,
          name: "Shravya",
        },
      ],
    };
  },
  computed: {
    filteredAndSorted() {
      const compare = (a, b) => {
        if (a.name < b.name) return -1;
        if (a.name > b.name) return 1;
        return 0;
      };

      return this.userList
        .filter((user) => {
          return user.name.toLowerCase().includes(this.search.toLowerCase());
        })
        .sort(compare);
    },
  },
  //...
};
</script>

to create the filteredAndSorted to return the userList array filtered and sorted.

We filter the values by the this.search value that we get from typing in the input.

v-model updates the this.search value with the latest input value.

Then we use v-for to render all the items in the filteredAndSorted array.

Conclusion

To filter on array with Vue.js, we can return the filtered array in a computed property.