[Vuejs]-Importing a common library into a Vue SPA

1👍

It sounds like you’re almost there.

Let’s assume that you want to do this:

import common from './scripts/common.js'

To achieve this we need common.js to have a default export. So something starting export default.

Further, let’s assume we want to access the objects and functions as common.dynamicYearColumn, common.formatPercent, etc.. Even ignoring the import/export part this implies that common needs to be an object with properties called dynamicYearColumn, formatPercent, etc.. Some of those properties will be functions but that doesn’t really make much difference.

So let’s briefly consider how we could build such an object.

const common = {}
common.dynamicYearColumn = { /* object properties here */ }
common.formatPercent = function (number) { /* implementation here */ }

Of course object literals allow us to define the object with these properties straightaway, rather than adding them later:

const common = {
  dynamicYearColumn: { /* object properties here */ },
  formatPercent: function (number) { /* implementation here */ }
}

ES6 added some syntactic sugar to simplify the creation of functions within an object, so this can be reduced down to:

const common = {
  dynamicYearColumn: { /* object properties here */ },
  formatPercent (number) { /* implementation here */ }
}

This is the object that we want to create within common.js and then export. Putting it all together we get:

export default {
  dynamicYearColumn: {
    // ...  
  },

  defaultPercentageColumn: {
    // ...
  },

  formatPercent (number) {
    // ...
  },

  numberWithCommas (n) {
    // ...
  }
}

Adding them to the Vue.prototype, as you are in your example, will make them available within your component as:

this.$common.formatPercent(25)

In your templates it would be:

{{ $common.formatPercent(25) }}

This is all good but note that you won’t be able to use the functions as filters. So you can’t write this:

{{ 25 | $common.formatPercent }}

If that’s something you want then you’ll have to register those functions as filters within your plugin.

Leave a comment