Categories
Vue Answers

How to Call a Filter from a Method Inside the Vue Component Instance?

Spread the love

Sometimes, we want to call a filter from a method inside the Vue component instance.

In this article, we’ll look at how to call a filter from a method inside the Vue component instance.

Call a Filter from a Method Inside the Vue Component Instance

We can call a filter from within the Vue component instance getting the filter function from the this.options.$filters property.

For instance, we can write:

<template>
  <div id="app">
    {{ truncatedText }}
  </div>
</template>

<script>
import Vue from "vue";

Vue.filter("truncate", (text, stop, clamp) => {
  return text.slice(0, stop) + (stop < text.length ? clamp || "..." : "");
});

export default {
  name: "App",
  computed: {
    truncatedText() {
      return this.$options.filters.truncate(
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit",
        10,
        "..."
      );
    },
  },
};
</script>

We have the truncatedText property that returns the truncated text .

The filter is defined by the Vue.filter method with the name as the first argument.

The 2nd argument is the filter function.

To call the truncate filter method, we use this.$options.filters.truncate with the text to truncate, stop with the number of characters of the truncated text, and clamp with the abbreviation symbol after the truncated text.

Then we display the text in the template.

Conclusion

We can call a filter from within the Vue component instance getting the filter function from the this.options.$filters property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *