Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue Mixin computed function pass parameters

Tags:

vue.js

vuejs2

So I wan't to be able to use my mixin just like the vue i18next library uses $t

<div>
      <strong>{{ $t("loadbundle", {lang: this.lang}) }}</strong>
</div>

and I can tell in the source code that it is a computed property in a mixin

  Vue.mixin({
    computed: {
      $t() {
        const getKey = getByKey(this._i18nOptions, this.$i18n ? this.$i18n.i18next.options : {});

        if (this._i18nOptions && this._i18nOptions.namespaces) {
          const { lng, namespaces } = this._i18nOptions;

          const fixedT = this.$i18n.i18next.getFixedT(lng, namespaces);
          return (key, options) => fixedT(getKey(key), options, this.$i18n.i18nLoadedAt);
        }

        return (key, options) =>
          this.$i18n.i18next.t(getKey(key), options, this.$i18n.i18nLoadedAt);
      },
    }

but I can't figure out how he made it possible to call it like a function and how does he get the parameters passed in.

I can't use a method because they get executed every time something updates.

like image 835
user3621898 Avatar asked Aug 03 '26 20:08

user3621898


1 Answers

Note the return (key, options) => ... bit: that returns a function! So the template invocation you wrote above first retrieves the value of the computed property (a function) and then invokes it with some parameters.

Effectively, all the up-front preparation of grabbing the $i18n object is done once, but the translation can still change if any of the parameters change (for example this.lang).

like image 109
Botje Avatar answered Aug 06 '26 10:08

Botje