I'm trying to create a global object I can use in Vue but having trouble accessing the methods. I want to use these methods in different components. Also, what's the best approach. I heard about using Mixins but I was thinking about trying a basic javascript object. I hope I'm asking this question the right way.
src/myobject.js
exports.myObj = () => {
function testMethod() {
console.log('working');
}
}
src/main.js
import Vue from 'vue'
import App from './App'
import { store } from './store/store'
import { myObj } from './myobject'
Vue.config.productionTip = false
myObj.testMethod() // NOT WORKING - TypeError: __WEBPACK_IMPORTED_MODULE_3_
/* eslint-disable no-new */
new Vue({
el: '#app',
store: store,
components: { App },
template: '<App/>'
})
src/components/App.vue
<template>
<div id="app">
<img src="./assets/logo.png">
</div>
</template>
<script>
export default {
name: 'App',
mounted: function () {
myObj.testMethod() // NOT WORKING
},
components: {
}
}
</script>
<style>
body {
margin: 0;
}
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
}
</style>
To create a simple ES module that exports both named functions and a default object, you can define it like this:
export function testMethod() {
console.log('working');
}
export function otherMethod() {
console.log('other method');
}
// optionally export a default object
export default {
testMethod,
otherMethod
}
Then, it will be possible to import it:
import { testMethod } from './myobject';
// or import the default export
import myObj from './myobject';
myObj.testMethod();
Now, to use it in your Vue components, there are multiple ways which I already explained in another answer. Using Vue mixins is one way (beware of global mixins) and writing a plugin is another way.
In your case, it could be a simple mixin:
// my-mixin.js
import { testMethod } from './myobject';
export default {
mounted() {
testMethod();
}
}
Hook functions with the same name are merged into an array so that all of them will be called.
<script>
// components/App.vue
import MyMixin from '../my-mixin'
export default {
name: 'App',
mixins: [MyMixin],
mounted() {
console.log('both this function and the mixin one will be called');
},
components: {
}
}
</script>
The reason your code doesn't work is because you're exporting a function which does nothing. testMethod isn't exposed, it's just declared within the exported function as a local function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With