eventBus, slot, sts 연결

2024. 3. 14. 18:11Daily Codig Reminder

eventBus

 

eventBus.vue

<script>
//script 태그만필요
import Vue from'vue'; 
var eventBus = new Vue(); //이벤트 버스 생성
export default eventBus;
</script>

 

 

HelloWorld.vue

<template>
  <div>
{{msg}}
<button @click="x" >HelloWorld2로 이벤트 전달</button>
  </div>
</template>

<script>
import eventBus from './EventBus';
export default {
  name:"HelloWorld",
  props:{
msg:String
  },

  methods:{
    x:function(){
      console.log("x호출됨");
      eventBus.$emit("xyz",100,"홍길동")//이벤트 전달명 xyz
    }
  }
}
</script>

<style>

</style>

 

 

HelloWorld2.vue

<template>
  <div>
    {{ msg }}
    <input type="text" v-bind:value="receiveData">
  </div>
</template>

<script>
import eventBus from './EventBus.vue';
export default {
  props:{
msg:String
  },
  created:function(){
    console.log("create호출됨======");
    eventBus.$on("xyz",this.receivemethod)
  },
  data:function(){
    return{
      receiveData:""
    }
  },
 methods:{
  receivemethod:function(v1, v2){
    console.log("receive 호출됨");
    this.receiveData=v1+'\t'+v2;
  }
 }
}
</script>

<style>

</style>

 

 

app.vue

<template>
  <div >
    
    <HelloWorld msg="이벤트버스(형제간의 데이터 전달방법)"/>
    <HelloWorld2 msg="이벤트버스2(형제간의 데이터 전달방법)"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import HelloWorld2 from './components/HelloWorld2.vue'

export default {
  name: 'App',
  components: {
    HelloWorld,
    HelloWorld2
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

EventBus

<script>
import Vue from 'vue';
var eventBus = new Vue(); //이벤트 버스 생성
export default eventBus;
</script>

Input.vue

<template>
    <div>
      <input type="text" v-model="data" @keyup.enter="add"><br>
    </div>
  </template>
  
  <script>
  import eventBus from './EventBus';
  export default {
    name:"Input",
    props:{},

    data() {
      return {
        data: ""
      };
    },
    methods: {
      add:function() {
        // "enter" 키가 눌렸을 때 호출되는 함수
        console.log("Enter key pressed! Data:", this.data);
        // 여기에서는 원하는 동작을 수행하거나 데이터를 활용할 수 있습니다.
        eventBus.$emit('xyz', this.data);
        this.data="";
      }
    }
  };
  </script>
  
  <style>
  
  </style>

 

 

list.vue

<!-- List.vue -->

<template>
  <div>
    <ul>
      <li v-for="(data, index) in todoList" :key="index">
        {{ index + 1 }}. {{ data }}
        <button @click="del(index)">삭제</button>
      </li>
    </ul>
   
  </div>
</template>

<script>
  import eventBus from './EventBus';

export default {
  data() {
    return {
     todoList: [] // 배열로 초기화
    };
  },
  created() {
    // 이벤트 버스를 통해 데이터를 수신
    eventBus.$on('xyz', this.add);
  },
  methods: {
    add:function(m) {
      // "xyz" 이벤트를 수신하면 데이터를 처리하여 로컬 상태에 추가
      this.todoList.push(m);
    },
   
   del:function(index) {
      // 선택된 인덱스의 항목을 로컬 상태에서 제거
      this.todoList.splice(index, 1);
    }
  }
};
</script>

<style>
</style>

 

 

App.vue

<template>
  <div id="app">
    
    <HelloWorld />
    <Input/>
    <List/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'
import List from './components/List.vue';
import Input from './components/Input.vue';
export default {
  name: 'App',
  components: {
    HelloWorld,
    List,
    Input
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 


slot

 

<template>
  <div id="app">
    
    <HelloWorld msg="slot 을 통한 태그의 전달">
    <!--html태그를 전달할 경우 slot 을 사용함-->
    <!--slot 영역-->
    <div>아름다운 밤입니다</div>
    <!--slot 영역-->
  </HelloWorld>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

<template>
  <div>
   <h1>{{ msg }}</h1>
   <slot></slot>
  </div>
</template>

<script>
export default {
  props:{
msg:String
  },
  data:function(){
    return{
     
    }
  },
  methods:{
    
  }
}
</script>

<style>

</style>

 

App.vue

<template>
  <div id="app">
    
    <HelloWorld msg="slot을 통한 태그의 전달"
    v-bind:headerText="A.header"
    v-bind:footer="A.footer"
    >
    <!--html태그를 전달할 경우 slot을 사용-->
    <!--slot 영역-->
    <div>
{{ A.message }}
{{ A.header }}
{{ A.footer }}
    </div>
    <!--slot 영역-->
    </HelloWorld>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  data:function(){
    return{
      A:{
        header:"오바마",
        message:"저의 동료...",
        footer:"2000/01/01"
      },
      B:{
        header:"샌더슨",
        message:"저의 동료...",
        footer:"2024/02/01"
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

 

HelloWorld.vue

<template>
  <div>
    <h1>{{ msg }}</h1>
    <div class="content">
      <slot></slot>
    </div>
<div class="footer">{{ footerText }}</div>
  </div>
</template>

<script>
export default {
  props:{
    msg:String,
    heaaderText:String,
    footerText:String
  }
  
}
</script>

<style>
.content{
  color: rebeccapurple;
}
.footer{
  color: blue;
}
</style>

 

 

 

src_14_slot4_SpeechBox_named

helloWorld.vue

 

<template>
  <div>
    <h1>{{ msg }}</h1>
   
      <slot name="headerText"></slot>
      <slot name="speechBox"></slot>
      <slot name="footerText"></slot>
    </div>

</template>

<script>
export default {
  props:{
    msg:String,
    heaaderText:String,
    footerText:String
  }
  
}
</script>

<style>
.content{
  color: rebeccapurple;
}
.footer{
  color: blue;
}
</style>

 

 

App.vue

<template>
  <div id="app">
    
    <HelloWorld msg="slot을 통한 태그의 전달">
    <!--html태그를 전달할 경우 slot을 사용-->
    <!--slot 영역-->
    
      <div slot="headerText">
      {{ A.header }}
    </div>
    <div slot="speechBox">
      {{ A.message }}
    </div>

<div slot="footerText">
{{ A.footer }}
</div>
    
    <!--slot 영역-->
    </HelloWorld>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  data:function(){
    return{
      A:{
        header:"오바마",
        message:"저의 동료...",
        footer:"2000/01/01"
      },
      B:{
        header:"샌더슨",
        message:"저의 동료...",
        footer:"2024/02/01"
      }
    }
  }
}
</script>

<style>

</style>

axois(비동기동작) - npm 명령을 통해 별도 설치 필요

 

C:\vue\vue_stu>npm install -- save axios

 

HelloWorld.vue

<template>
  <div>
    <h1>{{ msg }}</h1>
   <table border="1">
<tr>
  <th>부서번호</th>
  <th>부서이름</th>
  <th>위치</th>
</tr>
<tr v-for="(dept,i) in list" v-bind:key="i"> 
  <th>{{ dept.deptno }}</th>
  <th>{{ dept.dname }}</th>
  <th>{{ dept.loc }}</th>
</tr>
   </table>
    </div>

</template>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
import axios from 'axios';
export default {
  props:{
    msg:String
  },
  data:function(){
    return{
      list:[] //부서목록 저장
    }
  },
  created:function(){
this.deptList();
  },
  methods:{
    deptList:function(){
      //스프링에서 서버 가동 후 브라우저에서 서버 주소 복붙
      //yarn serve 시 node-module 없다는 에러 발생시

      var xxx = this.list; // => 에서 사용하기 위해 따로 저장
      // xxx와 list 는 같은 배열임. get 방식요청
      axios.get("http://localhost:8026/app/")
      .then(
        (res)=>{
          console.log(res);
          console.log("응답완료");
          res.data.map(function(ele,idx){
            xxx.push(ele);
          }
          )
        }
      ).catch(
        (error)=>{console.log(error);}
      )
console.log("get 이후 처리 코드====")
    }
  }

  
}
</script>

<style>
.content{
  color: rebeccapurple;
}
.footer{
  color: blue;
}
</style>

 

 

 

app.vue

<template>
  <div id="app">
    
    <HelloWorld msg="axios 실습" />

  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

 

<template>
  <div id="app">
    <DeptAdd msg="자식"/>
    <DeptAdd2 msg="자식"/>
    <DeptList msg="List"/>

  </div>
</template>

<script>
import DeptAdd from './components/DeptAdd'
import DeptAdd2 from './components/DeptAdd2.vue';
import DeptList from './components/DeptList.vue'
export default {
  name: 'App',
  components: {

    DeptAdd,
    DeptAdd2,
    DeptList
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

 

<script>
import Vue from 'vue';
var eventBus = new Vue(); //이벤트 버스 생성
export default eventBus;
</script>

 

 

DeptList.vue

<template>
  <div>
    {{ msg }}
    <table border="1">
<tr>
  <th>부서번호</th>
  <th>부서이름</th>
  <th>위치</th>
</tr>
<tr v-for="(dept,i) in list" v-bind:key="i"> 
  <th>{{ dept.deptno }}</th>
  <th>{{ dept.dname }}</th>
  <th>{{ dept.loc }}</th>
</tr>
   </table>
  </div>
</template>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
import eventBus from './EventBus';
import axios from 'axios';
export default {
  props:{
    msg:String
  },
  data:function(){
    return{
      list:[] //부서목록 저장
    }
  },
created:function(){
  eventBus.$on("xyz", this.y);
  this.deptList();
},
beforeMount:function(){

},
methods:{
  deptList:function(){
    var xxx = this.list; // => 에서 사용하기 위해 따로 저장
      // xxx와 list 는 같은 배열임. get 방식요청
      axios.get("http://localhost:8026/app/")
      .then(
        (res)=>{
          console.log(res);
          console.log("응답완료");
          res.data.map(function(ele,idx){
            xxx.push(ele);
          }
          )
        }
      ).catch(
        (error)=>{console.log(error);}
      )
console.log("get 이후 처리 코드====")
  },
  y:function(dept){
  console.log("list dept==",dept);
  this.list.push(dept);
}
}

}
</script>

<style>

</style>

 

 

DeptAdd.vue

<template>
  <div>
    <h2>부서 등록 및 수정</h2>
    <form v-on:submit.prevent="add">
    부서번호:<input type="text" name="deptno" v-model="dept.deptno">
    부서이름:<input type="text" name="dname" v-model="dept.dname">
    부서위치:<input type="text" name="loc" v-model="dept.loc">
    <button>추가</button>
    </form>
  </div>
</template>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

import axios from 'axios';
import eventBus from './EventBus';

export default {
  props:{
    msg:String
  },
data:function(){
return{
  dept:{
    deptno:"",
    dname:"",
    loc:""
  }
}
},
methods:{
  add:function(){
    var dept = this.dept;
    console.log(dept);
    var url="http://localhost:8026/app/add"
    axios.post(url,
    {
      deptno:dept.deptno,
      dname:dept.dname,
      loc:dept.loc
    }).then(
      //문제없이 성공시
      (res)=>{
        eventBus.$emit("xyz",dept)
        //insert 성공후 event bus 에 dept 저장
      }
    ).catch(
      (error)=>{
        console.log(error);
      }
    )
  }
}
}
</script>

<style>

</style>

 

 

Add2

<template>
  <div>
    <h2>부서 등록 및 수정 - get</h2>
    <form v-on:submit.prevent="add">
    부서번호:<input type="text" name="deptno" v-model="dept.deptno">
    부서이름:<input type="text" name="dname" v-model="dept.dname">
    부서위치:<input type="text" name="loc" v-model="dept.loc">
    <button>추가</button>
    </form>
  </div>
</template>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>

import axios from 'axios';
import eventBus from './EventBus';

export default {
  props:{
    msg:String
  },
data:function(){
return{
  dept:{
    deptno:"",
    dname:"",
    loc:""
  }
}
},
methods:{
  add:function(){
    var dept = this.dept;
    console.log(dept);
    var url=`http://localhost:8026/app/add?deptno=${dept.deptno}&dname=${dept.dname}&loc=${dept.loc}`; 
    axios.get(url,
    ).then(
      //문제없이 성공시
      (res)=>{
        eventBus.$emit("xyz",dept)
        //insert 성공후 event bus 에 dept 저장
      }
    ).catch(
      (error)=>{
        console.log(error);
      }
    )
    ////////////////////////
     // axios.post(url,
    // {
    //   deptno:dept.deptno,
    //   dname:dept.dname,
    //   loc:dept.loc
    // }).then(
    //   //문제없이 성공시
    //   (res)=>{
    //     eventBus.$emit("xyz",dept)
    //     //insert 성공후 event bus 에 dept 저장
    //   }
    // ).catch(
    //   (error)=>{
    //     console.log(error);
    //   }
    // )
  }
}
}
</script>

<style>

</style>

 

sts

'Daily Codig Reminder' 카테고리의 다른 글

React  (0) 2024.03.17
부서 삭제, router@3 props, query, 라우팅  (0) 2024.03.14
click, event, preventDefault, eventBus  (0) 2024.03.14
v-if /v-for/ v-on event  (0) 2024.03.13
vue  (0) 2024.03.13