Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Created November 28, 2018 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christiannwamba/f5d8b849ee80cccdc6ddcf37b9597948 to your computer and use it in GitHub Desktop.
Save christiannwamba/f5d8b849ee80cccdc6ddcf37b9597948 to your computer and use it in GitHub Desktop.

Mixins and custom functions to enhance your Vue applications

If you are a Vue lover like me and you are craving a way to extend your Vue application and add more reusable functions across parts of your application, you have come to the right place. Vue mixins and directives are a powerful combination for making this dream come through.

If you are from an Object-Oriented Programming background, then you will see vue mixins as an imitation of parent classes. You will see directives are like helper functions you define to do some quick work that may not affect your application in any way.

If you do not have an OOP background, then think of mixins like a utility that you can design to be shared by multiple people. If you are thinking about an office, it would be the photocopier. If you are thinking about a mall, it would be the mall security. Basically resources that multiple parts of your application (think office workers, think store owners) share.

I really hope you got the picture. Now, let’s move on to really learning about it.

Prerequisites

  1. Knowledge of JavaScript
  2. You have at least built a Vue application. One with more than 5 components is a plus
  3. If you have shared the photocopier in the office, then you can take a seat in front here

Mixins

Vue documentation has a really simple and straightforward explanation for what mixins are and how they work. According to the docs, mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

In simpler terms, it means that I can create a component with its data, methods, life-cycle components and I can have other components extend it. Now, this is different from using components inside other components where you can have a custom component with a name like <vue-custom></vue-custom> inside your template.

Let’s see what we mean. Our mixin This mixin is going to hold basic configurations for our app like:

  • App name
  • Greeter method
  • Company name for copyright at the footer

Let’s create a simple mixin

export const myMixin = {
  data () {
    return {
      title: 'Mixins are cool',
      copyright: 'All rights reserved. Product of super awesome people'
    }
  },
  created: function () {
    this.greetings()
  },
  methods: {
    greetings: function () {
      console.log('Howdy my good fellow!')
    }
  }
}

Ok. That’s as simple as it gets for a mixin. Now, if we use this in our component, you will see the magic in it.

And to use this, we can do the following in our template:

new Vue({
  mixins: [myMixin],
  el: '#app'
})

Directives

Directives, on the other hand, are methods like v-for that you can create to modify elements on your template. You know how v-if hides your component if a condition is not met? How about we underline a long sentence with a directive. We can even change the text a little as a way of making it highlighted.

We can have global directives that we can register so that all components in our vue application can use it. We also have local directives that are specific to that particular component. Awesome right?

Let’s create a global directive now

// Register a global custom directive called `v-highlight`
Vue.directive('highlight', {
  // When the bound element is inserted into the DOM...
  inserted: function (el, binding) {
    // set the colour we added to the bind
    el.style.backgroundColor = binding.value ? binding.value : "blue"
    el.style.fontStyle = 'italic'
    el.style.fontSize = '24px'
  }
})

Now, if we use this directive, you should see that part of the text changed and clearly different from others.

And to use this, we can do the following in our template:

<template>
  <div>
    <p v-highlight>Hello There!</p>
    <p v-highlight="red">This is a red guy</p>
  </div>
</template>

Filters

This is the another of the customization helpers we will look at. Filters help us in many ways that the first time you encounter it, you might get angry that you didn’t know earlier. We can define filters globally or locally, just like directives.

Filters can be used to apply common formatting to text or some more heavy filtration to an array or object. They are JavaScript functions, so we can define them to take as many arguments as possible. Also, we can chain them and use multiple filters as well. Cool right?

Let’s define a simple filter to capitalize the first word of the body of text (really useful when displaying things like names supplied by your user)

Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

And to use this, we can do the following in our template:

<template>
  <div>
    <p>{{ firstname | capitalize }}</p>
  </div>
</template>

Now, anywhere we use this filter, the first character will always be capital.

Bringing it together

We are going to compose a simple vue application using everything we have above now. You can try it out on codepen and play with it in realtime to see what and what you can get out of it.

First, let’s define our mixin:

const myMixin = {
  data () {
    return {
      title: 'mixins are cool'
    }
  },
  created: function () {
    alert('Howdy my good fellow!')
  }
}

Then we define our directive:

[...]
Vue.directive('highlight', {
  inserted: function (el, binding) {
    el.style.color = binding.value ? binding.value : "blue"
    el.style.fontStyle = 'italic'
    el.style.fontSize = '24px'
  }
})

Now, let’s define our filter:

[...]
Vue.filter('capitalize', function (value) {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

Then, let’s initialize our Vue application:

[...]
new Vue({
  mixins: [myMixin],
  el: '#app'
})

Finally, the simple template to see if these things actually work:

<div id="app">
    <p v-highlight>{{title | capitalize}}</p>
    <p v-highlight="'red'">This is a red guy</p>
    <p>{{'this is a plain small guy' | capitalize}}</p>
<div>

And that’s it. Check out what it looks like on codepen and play with it https://codepen.io/chiefoleka/pen/mQKLxO

Conclusion

All the above we have mentioned come in handy when building applications that are likely to grow in complexity. You want to define many reusable functions or formatting in a way that they can be reused across components, so you do not have to define the same thing over and over again.

Most importantly, you want to have a single source of truth, from where you can make a change and it spreads to other places. I’m excited by the thought of the cool things you can build with these features. Please do share them with me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment