Skip to content

Commit

Permalink
063 - Socket Mixin 만들기
Browse files Browse the repository at this point in the history
  • Loading branch information
moosin76 committed Dec 8, 2021
1 parent 0fa043e commit 22a6ea3
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 9 deletions.
10 changes: 8 additions & 2 deletions src/main.js
Expand Up @@ -8,7 +8,8 @@ import plugins from './plugins';
import '@babel/polyfill'
import 'roboto-fontface/css/roboto/roboto-fontface.css'
import '@mdi/font/css/materialdesignicons.css'
import titleMixin from './mixins/title-mixin';

import Mixins from './mixins';

Vue.config.productionTip = false

Expand All @@ -17,7 +18,12 @@ export function createApp(ctx) {
const store = createStore();
sync(store, router);

Vue.mixin(titleMixin);
const mixins = Object.keys(Mixins);
for (const mixin of mixins) {
if(Mixins[mixin]) {
Vue.mixin(Mixins[mixin]);
}
}

const app = new Vue({
data: { url: ctx ? ctx.url : '' },
Expand Down
14 changes: 14 additions & 0 deletions src/mixins/index.js
@@ -0,0 +1,14 @@
import camelCase from "lodash/camelCase";

const requireModule = require.context('.', false, /\.js$/);
const modules = {};

requireModule.keys().forEach(filename => {
if(filename !== './index.js') {
const moduleName = camelCase(filename.replace(/(\.\/|\.js)/g, ''));
modules[moduleName] = requireModule(filename).default;
}
});
// console.log(Object.keys(modules));

export default modules;
32 changes: 32 additions & 0 deletions src/mixins/socket-mixin.js
@@ -0,0 +1,32 @@
function getMixin(vm) {
const {socket} = vm.$options;
if(socket) {
return typeof socket === 'function' ? socket.call(vm) : socket;
}
}

const serverMixin = null;

const clientMixin = {
data() {
return {
socketEvents : [],
}
},
mounted() {
const socket = getMixin(this);
if(socket) {
this.socketEvents = Object.keys(socket);
for(const ev of this.socketEvents) {
this.$socket.on(ev, socket[ev])
}
}
},
destroyed() {
for(const ev of this.socketEvents) {
this.$socket.off(ev)
}
}
}

export default process.env.VUE_ENV === 'server' ? serverMixin : clientMixin;
13 changes: 6 additions & 7 deletions src/views/Home.vue
Expand Up @@ -48,13 +48,12 @@ export default {
title() {
return this.title;
},
mounted() {
this.$socket.on("room:testmsg", (data) => {
console.log("room:testmsg", data);
});
},
destroyed() {
this.$socket.off("room:testmsg");
socket() {
return {
"room:testmsg": (data) => {
console.log("room:testmsg", data);
},
};
},
methods: {
toastTest1() {
Expand Down

0 comments on commit 22a6ea3

Please sign in to comment.