>  기사  >  웹 프론트엔드  >  VUE3 시작하기 예: 간단한 인스턴트 메시징 애플리케이션 구축

VUE3 시작하기 예: 간단한 인스턴트 메시징 애플리케이션 구축

PHPz
PHPz원래의
2023-06-15 20:52:401160검색

Vue3은 현재 사용 가능한 가장 진보된 JavaScript 프레임워크 중 하나이며 Vue.js의 차세대 버전입니다. Vue3은 더 나은 성능과 풍부한 기능을 제공할 뿐만 아니라 더 나은 개발 경험도 제공합니다. 이 기사에서는 Vue3를 사용하여 간단한 인스턴트 메시징 애플리케이션을 구축하는 방법을 소개합니다.

  1. 애플리케이션 구조 결정

애플리케이션 구축을 시작하기 전에 애플리케이션의 구조를 결정해야 합니다. 샘플 애플리케이션에서는 다음 구성 요소를 생성합니다.

  • App.vue: 다른 모든 구성 요소를 표시하는 애플리케이션의 주요 구성 요소입니다.
  • ChatList.vue: 사용자와 관련된 채팅 목록을 표시합니다.
  • ChatMessage.vue: 단일 채팅 메시지를 표시합니다.
  • ChatInput.vue: 사용자가 메시지와 상호 작용할 수 있는 입력 구성 요소를 제공합니다.
  1. 앱 만들기

앱 제작을 시작하기 전에 최신 버전의 Node.js와 Vue CLI가 컴퓨터에 설치되어 있는지 확인하세요.

애플리케이션을 생성하려면 Vue CLI를 사용하고 다음 명령을 실행하세요.

vue create chat-app

이렇게 하면 새로운 Vue3 애플리케이션이 생성됩니다. 그런 다음 화면의 지시에 따라 다음 옵션을 선택해야 합니다.

  • 수동 설치 기능 선택
  • Babel 및 Router 선택
  • 설치 질문 뒤에 "공백"이 있는 "ESLint+Prettier" 선택
  • 선택 “커밋 시 Lint 및 수정”
  1. 구성 요소 만들기

다음으로 애플리케이션의 구성 요소를 만들어야 합니다. /src/comComponents/ 디렉터리에 다음 파일을 생성할 수 있습니다:

  • App.vue
<template>
  <div class="chat-app">
    <ChatList />
    <ChatInput />
  </div>
</template>

<script>
import ChatList from "./ChatList";
import ChatInput from "./ChatInput";

export default {
  name: "App",
  components: {
    ChatList,
    ChatInput,
  },
};
</script>

<style>
.chat-app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  justify-content: space-between;
}
</style>
  • ChatList.vue
<template>
  <div class="chat-list">
    <ChatMessage v-for="message in messages" :key="message.id" :message="message" />
  </div>
</template>

<script>
import ChatMessage from "./ChatMessage";

export default {
  name: "ChatList",
  components: {
    ChatMessage,
  },
  data() {
    return {
      messages: [
        { id: 1, text: "Hello", author: "Alice" },
        { id: 2, text: "Hi there", author: "Bob" },
      ],
    };
  },
};
</script>

<style>
.chat-list {
  height: calc(100% - 64px);
  overflow-y: scroll;
  padding: 16px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}
</style>
  • ChatMessage.vue
<template>
  <div class="chat-message">
    <div class="chat-message-author">{{ message.author }}</div>
    <div class="chat-message-text">{{ message.text }}</div>
  </div>
</template>

<script>
export default {
  name: "ChatMessage",
  props: {
    message: {
      type: Object,
      required: true,
    },
  },
};
</script>

<style>
.chat-message {
  margin-bottom: 8px;
}

.chat-message-author {
  font-weight: bold;
  margin-bottom: 4px;
}

.chat-message-text {
  font-size: 16px;
}
</style>
  • ChatInput.vue
<template>
  <div class="chat-input">
    <input type="text" v-model="message" @keyup.enter="sendMessage" />
    <button @click="sendMessage">Send</button>
  </div>
</template>

<script>
export default {
  name: "ChatInput",
  data() {
    return {
      message: "",
    };
  },
  methods: {
    sendMessage() {
      this.$emit("send", this.message);
      this.message = "";
    },
  },
};
</script>

<style>
.chat-input {
  display: flex;
  height: 64px;
  padding: 16px;
}

.chat-input input {
  flex: 1;
  border-radius: 4px 0 0 4px;
  border: none;
  padding: 8px;
  font-size: 16px;
}

.chat-input button {
  border-radius: 0 4px 4px 0;
  border: none;
  background-color: #007aff;
  color: white;
  font-size: 16px;
  padding: 8px 16px;
  cursor: pointer;
}
</style>
  1. 상위 구성 요소의 상태 처리

우리 애플리케이션에서는 여러 구성 요소 간에 데이터를 공유해야 합니다. 따라서 상위 구성 요소에 상태를 설정하고 이를 모든 하위 구성 요소에 전달할 수 있습니다. App.vue에 다음 코드를 추가합니다.

<script>
import ChatList from "./ChatList";
import ChatInput from "./ChatInput";

export default {
  name: "App",
  components: {
    ChatList,
    ChatInput,
  },
  data() {
    return {
      messages: [
        { id: 1, text: "Hello", author: "Alice" },
        { id: 2, text: "Hi there", author: "Bob" },
      ],
    };
  },
  methods: {
    sendMessage(message) {
      const newMessage = {
        id: this.messages.length + 1,
        text: message,
        author: "You",
      };
      this.messages.push(newMessage);
    },
  },
};
</script>

이 코드는 메시지 배열을 초기화하고 각 메시지를 수신하여 메시지 배열에 추가하는 sendMessage 메서드를 추가합니다.

  1. 하위 구성 요소에서 이벤트 처리

이제 하위 구성 요소에서 sendMessage 이벤트를 처리하고 이를 상위 구성 요소로 보내야 합니다. ChatInput.vue에 다음 코드를 추가합니다.

<script>
export default {
  name: "ChatInput",
  data() {
    return {
      message: "",
    };
  },
  methods: {
    sendMessage() {
      this.$emit("send", this.message);
      this.message = "";
    },
  },
};
</script>

이 코드는 사용자가 메시지를 보낼 때 send 이벤트를 트리거하고 메시지 텍스트를 매개변수로 상위 구성 요소에 다시 보냅니다.

  1. 하위 구성 요소에 데이터 표시

마지막으로 하위 구성 요소에 데이터를 표시해야 합니다. ChatMessage.vue 및 ChatList.vue에서는 다음 코드를 사용합니다.

<ChatMessage v-for="message in messages" :key="message.id" :message="message" />

이 코드는 메시지 배열의 콘텐츠를 기반으로 ChatMessage 구성 요소를 표시합니다.

  1. 앱 실행

이제 앱이 준비되었습니다. 애플리케이션을 실행하려면 다음 명령을 실행하세요.

npm run serve

이렇게 하면 http://localhost:8080/에 액세스할 수 있는 로컬 개발 서버에서 애플리케이션이 시작됩니다.

요약

이 기사에서는 Vue3을 사용하여 간단한 인스턴트 메시징 애플리케이션을 구축하는 방법을 소개합니다. Vue CLI를 사용하여 애플리케이션과 구성 요소를 만드는 방법, 상위 구성 요소에서 상태를 설정하고 하위 구성 요소에서 이벤트를 처리하고 데이터를 표시하는 방법을 배웠습니다. 이 기사를 통해 Vue3를 사용하여 현대적인 대화형 웹 애플리케이션을 개발하고 다음 프로젝트를 위한 견고한 기반을 마련하는 방법을 배울 수 있습니다.

위 내용은 VUE3 시작하기 예: 간단한 인스턴트 메시징 애플리케이션 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.