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 ofthis.$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
2 Answers
Reset to default 14Just 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))
}