How to access a global function (Vue.prototype.myFn) from another function?

Viewed 6915

I am on a nuxt.js project and trying to create global functions and I am this error:

Cannot read property '$toggleBodyClass' of undefined

Here is my code (plugins/globals.js):

import Vue from 'vue';

Vue.prototype.$toggleBodyClass = (addRemoveClass, className) => {
  const elBody = document.body;

  if (addRemoveClass === 'addClass') {
    elBody.classList.add(className);
  } else {
    elBody.classList.remove(className);
  }
};

Vue.prototype.$setModalBackdrop = () => {
  this.$toggleBodyClass('addClass', 'modal-open'); // ** How to make this work? **
};

This work just fine when I use it in my component (components/myComp.vue):

<template>
  <div>
    <button @click="handelClick">Toggle Class</button>
  </div>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$toggleBodyClass('addClass', 'modal-open');
    },
  },
};
</script>

please help, thanks.

2 Answers

Just change your code from

this.$toggleBodyClass

to

Vue.prototype.$toggleBodyClass

In nuxt you can use inject function to make it accessible from context, vuex store etc also inject

export default ({ app }, inject) => {
  inject('myInjectedFunction', (string) => console.log('That was easy!', string))
}
Related