Valmislahendus 6

Siia natuke tutvustavat juttu.

In order to better understand how to create your own Vue.js plugins, we will create a very simplified version of a plugin that displays i18n (short for Internationalization) strings.

Let’s begin by setting up the plugin object. It is recommended to create it in a separate file and export it, as shown below to keep the logic contained and separate.

We want to create a translation function. This function will receive a dot-delimited keystring, which we will use to look up the translated string in the user-provided options. This is the intended usage in templates:

template

<h1>{{ $translate('greetings.hello') }}</h1>

Since this function should be globally available in all templates, we will make it so by attaching it to app.config.globalProperties in our plugin:

js

// plugins/i18n.js
export default {
  install: (app, options) => {
    // inject a globally available $translate() method
    app.config.globalProperties.$translate = (key) => {
      // retrieve a nested property in `options`
      // using `key` as the path
      return key.split('.').reduce((o, i) => {
        if (o) return o[i]
      }, options)
    }
  }
}

Our $translate function will take a string such as greetings.hello, look inside the user provided configuration and return the translated value.

The object containing the translated keys should be passed to the plugin during installation via additional parameters to app.use():

js

import i18nPlugin from './plugins/i18n'

app.use(i18nPlugin, {
  greetings: {
    hello: 'Bonjour!'
  }
})

Now, our initial expression $translate('greetings.hello') will be replaced by Bonjour! at runtime.

See also: Augmenting Global Properties