투케이2K

37. (VueJs) [Vue 3] - emitter 사용해 index.html 에서 vue 컴포넌트로 이벤트 알림 전달 실시 본문

VueJs

37. (VueJs) [Vue 3] - emitter 사용해 index.html 에서 vue 컴포넌트로 이벤트 알림 전달 실시

투케이2K 2022. 6. 9. 08:04
반응형

[개발 환경 설정]

개발 툴 : VS CODE

개발 언어 : Vue Js

 

[그림 설명]

cmd 설치 명령어 : C:\Users\tk\VueProject\test-project> npm install mitt --save

 

[main.js - 소스코드]

// [main.js 설명]
// 1. 애플리케이션 진입점으로 Vue 초기화, 폴더 , 전역, 컴포넌트 , 라이브러리 등록 수행 실시
// 2. import App 을 사용해 최상위 App.vue 컴포넌트 지정 실시
// 3. createApp mount 를 사용해 index.html 파일 div id 값 설정 및 렌더링 시작점 지정 실시
// 4. router : 라우터는 웹페이지 간의 이동하는 방법 및 경로를 설정해주는 파일입니다
// 5. app.config.globalProperties : 글로벌 변수를 선언합니다. 변수 명칭은 $변수명칭 을 지정합니다





// [애플리케이션 생성 실시]
import { createApp } from 'vue'
import App from './App.vue'
import routers from './commonRouters/router.js' // [router]
import globals from './commonGlobal/global.js' // [global]
import stores from './commonStore/store.js' // [store]

import mitts from 'mitt' // [mitt]

import axios from 'axios' // [axios]

import "bootstrap/dist/css/bootstrap.min.css" // [bootstrap]
import "bootstrap" // [bootstrap]





// [앱 생성 실시]
const app = createApp(App);





// [앱 글로벌 변수 선언 실시]

// [name / 이름]
//app.config.globalProperties.$name = "투케이"; 


// [store / 저장소]
app.config.globalProperties.$store = stores; 


// [mitt / 이벤트 버스 / index.html 사용 / window.mitt.on 함수 등록]
window.mitt = window.mitt || mitts();


// [mitt / 이벤트 버스 / 컴포넌트 내 사용 / this.$emitter.on 함수 등록]
const emitter = mitts();
app.config.globalProperties.$emitter = emitter; 


// [axios / http 통신]
app.config.globalProperties.$axios = axios; 






// [라우터 사용 설정]
app.use(routers);





// [글로벌 사용 설정]
app.use(globals);





// [스토어 사용 설정]
app.use(stores);





// [mitt 이벤트 버스 사용 설정]
app.use(mitts);




// [main 아이디 : 렌더링 시작점] 
app.mount('#main');
 

[index.html [알림 전송] - 소스코드]

<!DOCTYPE html>

<!-- 
[index.html 설명]
1. index.html 파일은 브라우저에 표시되는 메인 html 파일입니다
2. index.html 파일은 개별 생성된 components 파일을 표시해줍니다
3. body 내에 생성한 <div id="app"></div> 부분은 main.js 에서 지정한 컴포넌트들이 마운팅 된다
-->
   
<html lang="">


  <!-- [header 설정] -->
  <head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">

    <link rel="icon" href="<%= BASE_URL %>favicon.ico">

    <title><%= htmlWebpackPlugin.options.title %></title>

  </head>





  <!-- [style 설정] -->
  <style>    
  </style>





  <!-- [cdn 설정] -->




  
  <!-- [script 설정] -->
  <script>


    // [dom 생성 및 이벤트 상시 대기 실시] 
    document.addEventListener("DOMContentLoaded", ready);
    function ready(){
      console.log("");
      console.log("[index] : [window ready] : [start]");            
      console.log("");
    };





    // [html 최초 로드 및 이벤트 상시 대기 실시] 
    window.onload = function() {
      console.log("");
      console.log("[index] : [window onload] : [start]");
      console.log(""); 

      // [이벤트 버스 호출 실시]
      setUser();
    };





    // [html 화면 사이즈 변경 이벤트 감지]
    window.onresize = function() {
      console.log("");
      console.log("[index] : [window onresize] : [start]");
      console.log(""); 
    };




    // [자바스크립트 브릿지 호출 실시]
    function setUser() {
      console.log("");
      console.log("[index] : [setUser] : [start]");
      console.log(""); 

      // [vue 컴포넌트로 이벤트 알림 전달]
      window.mitt.emit("setUser", "투케이");
    };


  </script>





  <!-- [body 설정] -->
  <body>

    <!-- [main 아이디 지정 실시 : main.js 렌더링 시작점] -->
    <div id="main"></div>
    
  </body>

</html>
 

[App.vue [알림 받음] - 소스코드]

<!-- [애플리케이션 공통 스크립트 지정] -->
<script>


// [export 설정 실시]
export default {
  // [main.js 등록한 App 컴포넌트]
  name: 'App', 





  // [동적 변환 컴포넌트 페이지 : 기본 표시 부분]
  components: { 
  },





  // [컴포넌트 생성 시 초기 데이터 설정 (리턴 값 지정)]
  data () {
    return {
      data: "APP VUE" // [데이터 지정]
    }    
  },





  // [생명 주기 : 라이프 사이클]
  beforeCreate() {
    console.log("");
    console.log("[App] : [beforeCreate] : [start]");
    console.log("설 명 : 인스턴스 초기화 준비");
    console.log("");
  },
  created() {
    console.log("");
    console.log("[App] : [created] : [start]");
    console.log("설 명 : 인스턴스 생성 완료");
    console.log("");
  },
  beforeMount() {
    console.log("");
    console.log("[App] : [beforeMount] : [start]");
    console.log("설 명 : DOM 렌더링 준비");
    console.log("");
  },
  mounted() {
    console.log("");
    console.log("[App] : [mounted] : [start]");
    console.log("설 명 : DOM 렌더링 완료");
    console.log("");


    // [이벤트 버스 알림 받기 등록]
    window.mitt.on("setUser", this.setUser);
  },
  beforeUpdate() {
    console.log("");
    console.log("[App] : [beforeUpdate] : [start]");
    console.log("설 명 : DOM 상태 및 데이터 변경 시작");
    console.log("");
  },
  updated() {
    console.log("");
    console.log("[App] : [updated] : [start]");
    console.log("설 명 : DOM 상태 및 데이터 변경 완료");
    console.log("");
  },
  beforeUnmount() {
    console.log("");
    console.log("[App] : [beforeUnmount] : [start]");
    console.log("설 명 : 인스턴스 마운트 해제 준비");
    console.log("");
  },
  unmounted() {
    console.log("");
    console.log("[App] : [unmounted] : [start]");
    console.log("설 명 : 인스턴스 마운트 해제 완료");
    console.log("");


    // [이벤트 버스 알림 받기 해제]
    window.mitt.off("setUser");
  },





  // [메소드 정의 실시]
  methods: {

    // [실시간 이벤트 버스 알림 받기 함수 정의 실시]
    setUser: function(info){
      console.log("");
      console.log("[App] : [setUser] : [start]");
      console.log("info : " + info);
      console.log("");
    }
  }

}

</script>
 

[결과 출력]


 

반응형
Comments