I can't find much information on the web with explanation on how to use multiple vuejs instances and make them work together.
Please, can someone show me his code style on how to do that?
I have a main /resources/assets/js/app.js
:
Vue.component('google-maps', require('./components/Gmaps.vue'));
export const App = window.App = new Vue({
el: '#app',
mounted(){
// Listen for an event
socket.on('alarm-channel:App\\Events\\AlarmCreated', ({data}) => {
return this.alarmCreated(data.alarm);
});
},
data: {
users: [],
alarms: [] // #01 - should be in Alarms.js
},
methods: {
/* Newly registered alarm */
alarmCreated(alarm){
this.alarms.push(alarm); // #01 - should be in Alarms.js
}
}
});
How can I call a same new Vue()
inside /resources/assets/js/alarms.js
to make it work together ?:
cl3m :
Assuming you are using a bundler such as webpack, and are able to use ES6 modules, I would create a Vuex store in alarm.js:\n\n// npm install vuex\nimport Vuex from 'Vuex'\n\nexport const store = new Vuex.Store({\n state: {\n users: [],\n alarms: []\n },\n mutations: {\n addAlarm(state, alarm) {\n state.products.push(alarm)\n }\n },\n getters: {\n alarms: state => state.alarms,\n users: state => state.users\n },\n actions: {\n addAlarm: ({ commit }, alarm) => {\n commit('addAlarm', obj)\n }\n }\n})\n\n\nThen import it into app.js:\n\nimport Vuex from 'Vuex'\nimport { store } from './alarm.js'\n\nVue.use(Vuex)\n\nnew Vue({\n el: '#app',\n mounted() {\n // Listen for an event\n socket.on('alarm-channel:App\\\\Events\\\\AlarmCreated', ({\n data\n }) => {\n return this.alarmCreated(data.alarm);\n });\n },\n computed: {\n ...Vuex.mapGetters({\n alarms: 'alarms',\n users: 'users'\n })\n // or maybe?\n // alarms: _ => store.alarms\n },\n methods: {\n ...Vuex.mapActions({\n addAlarm: 'addAlarm'\n }),\n alarmCreated(alarm) {\n this.addAlarm(alarm)\n }\n }\n});\n\n\nI have not tested this code, you may have to tweak it a bit to suit your needs.\n\nThe ideal place for the store would be in a store directory, with an index.js file to load submodules.\n\nYou should definately have a look at the Vuex documentation ",
2017-09-09T20:57:13