1편 : https://velog.io/@rlagurwns112/Django-websocket-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0
chat.js//
export async function getChats() {
return await jwtApi.get('webchat/');
}
export const useWebChat = () => {
const authStore = useAuthStore();
const messages = ref([]);
const uid = computed(() => {
return authStore.loginUser?.uid || null;
});
if (uid.value) {
const { execute } = useAsyncState(getChats, [], {
immediate: false,
throwError: true,
onSuccess: response => {},
onError: err => {},
});
const { send, close, open, error, status } = useWebSocket(
`ws://127.0.0.1:8000/webchat?uid=${uid.value}`,
{
onConnected: async ws => {
try {
const chats = await execute();
messages.value = chats.data;
} catch (error) {
console.log(error);
}
},
onDisconnected: (ws, event) => {
if (event.code == 4001) {
console.log('Authentication Error');
}
},
onMessage: (ws, msg) => {
const newData = JSON.parse(msg.data);
messages.value = [...messages.value, newData.new_message];
},
onError: (ws, msg) => {},
},
);
return {
status,
messages,
send,
open,
close,
error,
};
}
};
사용한 라이브러리는 @vueuse/core의 useWebSocket을 사용
onConnected : 연결됐을때 실행되는 로직. 백엔드로 채팅목록 요청 보내고 받은걸 messages에 저장
onMessage : 백엔드에서 메세지 받았을때 실행되는 로직. 장고에서 해당 채팅을 프론트로 보내는 코드를 짰기 때문에 msg인자에 채팅 1개가 들어옴. 이 msg를 messages에 추가
알림기능 : 채팅과 비슷하다
이 코드를 바탕으로 실제 페이지에서 구현하기
webchat.vue//
...
...
<WebChatItem
v-for="data in webSocket?.messages?.value"
:key="data.id"
v-bind="data"
/>
...
...
여기서 messages is not found에러 뜸.
PostRightBar.vue//
...
...
<q-btn
padding="8px 12px 8px 8px"
unelevated
color="primary"
text-color="white"
class="full-width"
@click.prevent="showChatDialog"
>
<span class="text-weight-bold">방명록남기기</span>
<WebChat v-if="authStore.isLogin" v-model="dialogVisible" />
</q-btn>
...
...
v-if="authStore.isLogin" 으로 반응형 조건을 걸면 false일때 webchat 컴포넌트가 실행이 안되고 true로 바뀌면 자동으로 컴포넌트가 등록되어 내부 로직이 실행됨!!(알림도 동일)