To distribute pure functions (without side effects) you can use mixins.
const mixin = {
methods:{
foo() {
console.log('foo')
}
}
}
Then you can define the mixin in the vue instance:
new Vue({
mixins: [mixin],
// ...
})
This function can now be used in every component as if it where defined there.
Your mqtt connection is quite another story. You are sharing the result of mqtt.connect. This function does not return a function, so it cannot be shared via methods. Furthermore: This function creates state. A good way to share state is Vuex. With Vuex you can share state across multiple components and define mutations.
Define a store in src/store/index.js:
const store = new Vuex.Store({
state: {
connected: false,
result: null
},
mutations: {
setMqtt (state, mqttResult) {
state.connected = true
state.result = mqttResult
}
}
})
Add it to your app:
import store from './store'
new Vue({
el: '#app',
mixins: [mixin],
store,
// ....
})
Now you can access this store in each component, with:
this.$store.state.connected
this.$store.state.result
The access should only be done in functions that are defined in computed. As soon as any change occurs in the state, all functions defined in computed are evaluated again.
Now you can fetch the data in your main file and commit the result:
mqtt.connect('mqtt://server:8083').on('connect', (someData) => {
store.commit('setMqtt', someData)
})
Links to the official docs:
https://v2.vuejs.org/v2/guide/mixins.html
https://vuex.vuejs.org/
toto?foo