Vue3에서 websocket 사용하기

김혁준·2024년 2월 23일
0

Vue3

목록 보기
3/5

1편 : https://velog.io/@rlagurwns112/Django-websocket-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0

  1. 채팅기능 구현
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에 추가

  1. 알림기능 : 채팅과 비슷하다

  2. 이 코드를 바탕으로 실제 페이지에서 구현하기

  • 목표 : 유저가 로그인 했을때만 연결되도록 하고 싶다
  • 첫번째 삽질 : 유저가 로그인 하면 유저의 로그인 여부를 true로 스토어에 저장했는데, 이걸 watch로 감시하면서 하려고 했더니 새로운 객체가 만들어버려져서 오류가 뜸.
    - 이유 : 연결할때 파라미터로 유저 id를 넣어주는데 새로운 객체로 연결된게 코드에 반영이 안됌.
webchat.vue//
...
...
<WebChatItem
          v-for="data in webSocket?.messages?.value"
          :key="data.id"
          v-bind="data"
        />
...
...

여기서 messages is not found에러 뜸.

  • 해결방법 : v-if를 사용해서 조건에 따라 컴포넌트가 등록되도록 코드 수정
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로 바뀌면 자동으로 컴포넌트가 등록되어 내부 로직이 실행됨!!(알림도 동일)

0개의 댓글

관련 채용 정보