Я удалил vuex-shared-mutations и нашел обходной путь. Я надеюсь, что есть гораздо лучший способ достичь этого. Если да, пожалуйста, дайте мне знать!
myStore.js (фрагмент с соответствующим кодом)
import store from '@/store';
function addDataToStore(state, message) {
// Contains logic to add whatever data you have to the store
}
const channel = new BroadcastChannel('browser-tabs-test');
channel.onmessage = (event) => {
if (event.data.type === 'myCopy') {
console.log('This browser tab received a copy of the original data);
// Call a mutation so a class that is subscribed (aka this.$store.subscribe)
// will be alerted that this store instance has been updated with this data
store.commit('myStore/SOCKET_ONMESSAGE_COPY', event.data.message);
}
};
mutations: {
SOCKET_ONMESSAGE(state, message) {
console.log(`Received ${message}`);
channel.postMessage({ type: 'myCopy', message });
addDataToStore(state, message);
},
// Having a similar but separate mutation avoids infinite loops that
// would occur with the broadcast channel posting messages
SOCKET_ONMESSAGE_COPY(state, message) {
console.log(`Received Copy of ${message}`);
addDataToStore(state, message);
},
},
myTest.vue (фрагмент с соответствующим кодом)
created() {
this.$store.subscribe((mutation) => {
if (mutation.type === 'myStore/SOCKET_ONMESSAGE' ||
mutation.type === 'myStore/SOCKET_ONMESSAGE_COPY'
) {
console.log(`Received via subscription ${mutation.payload} from ${mutation.type}`);
// Do something with the payload in this instance of the class
}
}
},
При использовании этого кода:
- вкладка 1 браузера принимает только события SOCKET_ONMESSAGE и
- вкладка 2 браузера принимает только события SOCKET_ONMESSAGE_COPY