Categories
Vue Answers

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

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.

Categories
Vue Answers

How to Set the Background Image of an Element with Vue.js?

Sometimes, we want to set the background image of an element with Vue.js.

In this article, we’ll look at how to set the background image of an element with Vue.js.

Set the Background Image of an Element with Vue.js

We can set the background image of an element with Vue.js by setting the ‘background-image' property to the path of the background image.

For instance, we can write:

<template>
  <div id="app">
    <div
      :style="{
        'background-image': `url(${require(image)})`,
        width: '100px',
        height: '100px',
      }"
    ></div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      image: "@/assets/logo.png",
    };
  },
};
</script>

to do this.

We add the style prop with the 'background-image' property to set the background-image CSS property.

Then we pass in the image path with require with the image path in the Vue project folder to compute the correct path.

Now when we should see the background image displayed.

Conclusion

We can set the background image of an element with Vue.js by setting the ‘background-image' property to the path of the background image.

Categories
Vue Answers

How to Do Something When Hit the Enter Key in Vue.js?

Sometimes, we want to do something when we hit the enter key in Vue.js.

In this article, we’ll look at how to do something when we hit the enter key in Vue.js.

Do Something When Hit the Enter Key in Vue.js

We can do something when we hit the enter key by adding the v-on:keyup directive to the element that does something when we hit the enter key.

For instance, we can write:

<template>
  <div id="app">
    <input v-on:keyup.enter="onEnter" />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

We add the v-on:keyup directive with the enter modifier to let us watch for enter key presses.

We set its value to the onEnter method to run it when we focused on the input and press enter.

Also, we can shorten this slightly by using @ instead of v-on: .

To do this, we write:

<template>
  <div id="app">
    <input @keyup.enter="onEnter" />
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

In either example, we should see 'pressed enter' logged when we focus on the input and press enter.

Conclusion

We can do something when we hit the enter key by adding the v-on:keyup directive to the element that does something when we hit the enter key.

Categories
Vue Answers

How to Deep Watch an Array of Objects and Calculating the Change with Vue.js?

Sometimes, we want to deep watch an array of objects and calculating the change with Vue.js.

In this article, we’ll look at how to deep watch an array of objects and calculating the change with Vue.js.

Deep Watch an Array of Objects and Calculating the Change with Vue.js

We can deep watch an array of objects and calculate the change with Vue.js with watchers.

For instance, we can write:

App.vue

<template>
  <div id="app">
    <Person :person="person" v-for="person in people" :key="person.id"></Person>
  </div>
</template>

<script>
import Person from "@/components/Person";

export default {
  name: "App",
  components: {
    Person,
  },
  data() {
    return {
      people: [
        { id: 0, name: "Bob", age: 27 },
        { id: 1, name: "Frank", age: 32 },
        { id: 2, name: "Joe", age: 38 },
      ],
    };
  },
};
</script>

Person.vue

<template>
  <div class="hello">
    <div class="person">
      {{ p.name }}
      <input type="text" v-model="p.age" />
    </div>
  </div>
</template>

<script>
export default {
  name: "Person",
  props: {
    person: Object,
  },
  data() {
    return {
      p: {},
    };
  },
  watch: {
    p: {
      handler(newValue) {
        console.log(newValue.id);
        console.log(newValue.age);
      },
      deep: true,
    },
  },
  mounted() {
    this.p = { ...this.person };
  },
};
</script>

In App.vue , we have the people array that’s used to render the Person component with v-for .

We pass in the person as the value of the person prop.

Then in Person , we add the props property to accept the person prop.

And we have the p reactive property which we set to the copy of person as its value in the mounted hook.

In the p watcher in the watch property, we log the newValue value.

We set the deep option to true to let us watch for changes in objects.

And in the template, we render p.name and bind p.age as to the input value of the text input.

Now when we type into the text input, the p watcher should run and log the newValue.age value.

Conclusion

We can deep watch an array of objects and calculate the change with Vue.js with watchers.

Categories
Vue Answers

How to Make Helper Functions Globally Available to Single-File Components with Vue.js?

Sometimes, we want to make helper functions globally available to single-file components with Vue.js.

In this article, we’ll look at how to make helper functions globally available to single-file components with Vue.js.

Make Helper Functions Globally Available to Single-File Components with Vue.js

We can create mixins to make helper functions globally available to single-file components with Vue.js.

For instance, we can write:

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

<script>
import Vue from "vue";

Vue.mixin({
  methods: {
    capitalizeFirstLetter: (str) => str[0].toUpperCase() + str.slice(1),
  },
});
export default {
  name: "App",
  data() {
    return {
      name: "james",
    };
  },
  computed: {
    capitalizedName() {
      return this.capitalizeFirstLetter(this.name);
    },
  },
};
</script>

We call Vue.mixin with an object to make our own mixin.

It creates a global mixin so it’ll be available to all components automatically.

In the object, we have the methods property which is set to an object with some component methods.

It has the capitalizeFirstLetter method which takes a string and returns a string with the first letter capitalized.

Next, we return the name reactive property in the data method.

And then we create the capitalizedName computed property which calls the capitalizeFirstLetter method from the mixin with this.name and returns the returned result.

Next, we add capitalizedName to the template to render it.

And we see ‘James’ displayed as a result.

Conclusion

We can create mixins to make helper functions globally available to single-file components with Vue.js.