最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to access a global function (Vue.prototype.myFn) from another function? - Stack Overflow

programmeradmin3浏览0评论

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 ponent (ponents/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.

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 ponent (ponents/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.

Share Improve this question edited Sep 2, 2020 at 3:42 Syed asked Jan 6, 2019 at 14:33 SyedSyed 16.5k13 gold badges126 silver badges157 bronze badges 2
  • Have you tried Vue.prototype.$toggleBodyClass instead of this.$toggleBodyClass? – Sami Hult Commented Jan 6, 2019 at 14:39
  • @SamiHult wow! that simply worked :) thanks. Can you add this as answer I'll mark it accepted. – Syed Commented Jan 6, 2019 at 14:55
Add a ment  | 

2 Answers 2

Reset to default 14

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))
}
发布评论

评论列表(0)

  1. 暂无评论