click, event, preventDefault, eventBus

2024. 3. 14. 17:20Daily Codig Reminder

event01_click2

<template>
  <div id="app">
    
    <HelloWorld msg="이벤트 실습"/>
  </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>{{ result }}</h1>
    값1: <input type="text" v-model="num1" />
    값2: <input type="text" v-model="num2" />
    <button @click="sum('+')">+</button>
    <button @click="sum('-')">-</button>
    <button @click="sum('*')">*</button>
    <button @click="sum('/')">/</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      num1: "",
      num2: "",
      result: null
    };
  },
  methods: {
    sum(e) {
      this.result = parseInt(this.num1) + parseInt(this.num2);

      switch (e) {
        case '-':
          this.result = parseInt(this.num1) - parseInt(this.num2);
          break;
        case '*':
          this.result = parseInt(this.num1) * parseInt(this.num2);
          break;
        case '/':
          this.result = parseInt(this.num2) !== 0 ? parseInt(this.num1) / parseInt(this.num2) : "Error: Division by zero";
          break;
        default:
          // For addition, no need to modify this.result, as it's already set above
      }

      return this.result;
    }
  }
};
</script>

<style>

</style>

<template>
  <div>
    <h1>이벤트 실습</h1>
가격: <input type="text" v-model="price"><br>
갯수:
<select @change="sum" v-model="quantity">
<option value="10">10</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<br>
<span>{{ total }}</span>
  </div>
</template>

<script>
export default {
  data:function(){
    return{
      price:"",
      quantity:"",
      total:""
    }
  },
  methods:{
    sum:function(){
      this.total=Number.parseInt(this.price)*Number.parseInt(this.quantity);
    }
  }
}
</script>

<style>

</style>

<template>
  <div>
    <h1>도서목록{{ msg }}</h1>
    <div v-for="(book, idx) in booklist" :key="idx">
      <input type="checkbox" v-model="books" :value="book.name" />
      {{ book.name }}, {{ idx }}번, 가격: {{ book.price }}
      <button @click="del" :data-idx="idx">삭제</button>
    </div>
    <hr />
    <button @click="allDel">선택삭제</button>
  </div>
</template>

<script>
export default {
  props: {
    msg: String,
  },
  data() {
    return {
      booklist: [
        { name: "자바의 정석", price: 3000 },
        { name: "jsp 정석", price: 4000 },
        { name: "spring 정석", price: 5000 },
        { name: "jquery 정석", price: 5000 },
        { name: "angular 정석", price: 7000 },
      ],
      books: [], // 선택된 책 목록 저장
    };
  },
  methods: {
    del(e) {
      var delIdx = e.target.dataset.idx;
      console.log(delIdx);
      this.booklist.splice(delIdx, 1);
    },
    allDel() {
      var xx = this.booklist;
      console.log(this.books); //'자바의 정석','spring 정석','jsp 정석'
      this.books.map((ele, idx) => {
        console.log(this);
        xx.map((e, i) => {
          if (ele == e.name) {
            console.log(i, idx); //전체 책의 idx 값
            xx.splice(i, 1); //1개 삭제
          }
        });
      });
    },
  },
};
</script>

<style></style>

 

람다

 

<template>
  <div>
    <h1>도서목록{{ msg }}</h1>
    <div v-for="(book, idx) in booklist" :key="idx">
      <input type="checkbox" v-model="books" :value="book.name" />
      {{ book.name }}, {{ idx }}번, 가격: {{ book.price }}
      <button @click="del" :data-idx="idx">삭제</button>
    </div>
    <hr />
    <button @click="allDel">선택삭제</button>
  </div>
</template>

<script>
export default {
  props: {
    msg: String,
  },
  data() {
    return {
      booklist: [
        { name: "자바의 정석", price: 3000 },
        { name: "jsp 정석", price: 4000 },
        { name: "spring 정석", price: 5000 },
        { name: "jquery 정석", price: 5000 },
        { name: "angular 정석", price: 7000 },
      ],
      books: [], // 선택된 책 목록 저장
    };
  },
  methods: {
    del(e) {
      var delIdx = e.target.dataset.idx;
      console.log(delIdx);
      this.booklist.splice(delIdx, 1);
    },
    allDel() {
      var xx = this.booklist;
      console.log(this.books); //'자바의 정석','spring 정석','jsp 정석'
      this.books.map((ele, idx) => {
        console.log(this);
        xx.map((e, i) => {
          if (ele == e.name) {
            console.log(i, idx); //전체 책의 idx 값
            xx.splice(i, 1); //1개 삭제
          }
        });
      });
    },
  },
};
</script>

<style></style>


 

이벤트

@click="prevent”

preventDefault();

target.html로 이동

 

<template>
  <div>
    <h1>{{ msg }}</h1>
<a href="https://www.daum.net" @click="prevent">다음 -preventDefault</a><br>
<a href="https://www.google.com" target="_blank">구글</a><br>
<form action="target.html" @submit="prevent">
  <button>전송</button>
</form>
  </div>
</template>

<script>
export default {
  props:{
    msg:String
  },
  
  methods:{
    prevent:function(e){
      console.log("함수호출됨");
      e.preventDefault();
      
    }
  }
}
</script>

<style>

</style>

이벤트 수식어

<template>
  <div>
    <h1>{{ msg }}</h1>
    <button @click="x" >x()</button><br>
    <button v-on:click.once="x">x() once</button><br>
    <h1>2. preventDefault이벤트 수식어</h1>
    <a href="https://www.daum.net" @click="y">다음1 y</a><br>
    <a href="https://www.daum.net" v-on:click="y2" target="_blank">다음2 y2</a><br>
    <a href="https://www.daum.net" v-on:click.prevent="y2" target="_blank">다음2 prevent</a><br>
    <h1>2.이벤트 전파방지</h1>
    <div style="background-color: yellow" @click="aaa">
aaa
<div style="background-color: green" @click="bbb">bbb</div>
</div>
<hr>
    <h1>3. stop 이벤트 수식어</h1>
    
<div style="background-color: yellow" @click="aaa">
aaa
<div style="background-color: red" @click="bbb">bbb</div>
</div>
<hr>
<div style="background-color: yellow" @click="aaa">
aaa
<div style="background-color: red" @click.stop="bbb">bbb</div>
</div>
<h1>4. 이벤트 수식어</h1>
<input type="text" @keyup="xyz" >keyup<br>
<input type="text" v-on:keyup.enter="xyz" >keyup.enter<br>
<h1>5. ctrl</h1>
<input type="text" @keyup.ctrl.enter="xyz" >keyup.ctrl.enter<br>
<input type="text" v-on:keyup.ctrl.up="xyz" >keyup.ctrl.up<br>
  </div>
</template>

<script>
export default {
 
  methods:{
    aaa:function(){
      console.log("aaa===");
    },    
    bbb:function(e){
      console.log("bbb===");
      e.stopPropagation();
      
    },
    x:function(){
      console.log("x===");
    }, 
    y:function(){
      console.log("y===");
    }, 
    y2:function(){
      console.log("y2===");
    },
    xyz:function(){
      console.log("xyz===");
    }
  }
}
</script>

<style>

</style>

emit

 

app.vue

<template>
  <div>
    <h1>이벤트 실습</h1>
    <!--자식에서 부모로 데이터 전송은 이벤트를 이용-->
    <!--자시겡서는 이벤트를 emit 하고 부모는 v-on을 이용하여 수신한다-->
    <!--this.$emit("xyz") :이벤트 명칭 전달 => v-on:xyz="recieve"-->
<button @click="xyz" >부모에게 데이터 전송1</button><br>
<!--//1. 이벤ㅌ 발생-->
<button @click="xyz2" >부모에게 실제데이터 전송2</button><br>
<!--//1. 이벤트 발생 , 데이터 전달-->
</div>
</template>

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

      console.log("xyz========", this);
      this.$emit("xyz"); //2.이벤트 명칭을 부모에게 이벤트
      //"xyz "로 전달
    },
    xyz2:function(){

console.log("xyz2========", this);
this.$emit("xyz2",100,"홍길동"); //2.이벤트 명칭을 부모에게 이벤트
//"xyz "로 전달
}
  }
}
</script>

<style>

</style>

 

<template>
  <div id="app">
    
    <HelloWorld msg="이벤트"
    v-on:xyz="recieve1"
    v-on:xyz2="recieve2"
    />
    <!-- 3.이벤트 발신명으로 수신, 처리함수 등록-->
  </div>
</template>

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

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods:{
    recieve1:function(){
      console.log("부모가 xyz이벤트를 받아 receieve 를 실행함")
    },
    recieve2:function(value1, value2){
      console.log("부모가 xyz이벤트를 받아 receieve함수 호출: " ,value1, value2)
    }
  }
}
</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>

BookList

App.vue

<template>
  <div id="app">
    선택한 책이름 :{{ bookName }}
    <bookList msg="BookList exam" v-bind:bookList="list"
    v-on:xyz="receive"
    />
  </div>
</template>

<script>
import bookList from './components/BookList'

export default {
  name: 'App',
  components: {
    bookList
  }
  ,
    data:function(){
      return{
      list:[
      {
          id: "p01",
          name: "위험한 식탁",
          price: 2000,
          date: "20170401",
          img: "a",
        },
        {
          id: "p02",
          name: "공부의 비결",
          price: 3000,
          date: "20170402",
          img: "b",
        },
        {
          id: "p03",
          name: "오메르타",
          price: 2500,
          date: "20170401",
          img: "c",
        },
        {
          id: "p04",
          name: "행복한 여행",
          price: 4000,
          date: "20170401",
          img: "d",
        },
        {
          id: "p05",
          name: "해커스 토익",
          price: 2000,
          date: "20170401",
          img: "e",
        },
        {
          id: "p06",
          name: "도로 안내서",
          price: 2000,
          date: "20170401",
          img: "f",
        }
      ],
      bookName:""
     
    }
      
  
    },
    methods: {
      receive:function(data) {
      console.log(data);
      this.bookName = data;
    },
  },
}
</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>

 

 

 

BookList.vue

<template>
    <div>
      <h2>{{ msg }}</h2>
    <ul v-for="(book, index) in bookList" :key="index">
      <a @click ="xyz">
      <img v-bind:src="require(`../assets/image/${book.img}.jpg`)"
width="100" height="100"
v-bind:data-xxx="book.name">
    </a>
      {{ book.name }}
    </ul>

  </div>
  </template>
  
  <script>
 export default {
  name:"BookList",
  props: {
    msg: String,
    bookList: Array,
  },
  methods: {
   xyz:function(e) {
    console.log(e.target.dataset.xxx);
      this.$emit("xyz", e.target.dataset.xxx);
    },
  },
};
  </script>
  
  <style>
  
  </style>

클릭시 HelloWorld2로 이벤트 전달

 

EventBus.vue

<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")//이벤트 전달명 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.receive)
  },
  data:function(){
    return{
receiveData:""
    }
  },
 methods:{
  receive:function(){
    console.log("receive 호출됨");
    this.receiveData="형제가 호출완료";
  }
 }
}
</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>

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

부서 삭제, router@3 props, query, 라우팅  (0) 2024.03.14
eventBus, slot, sts 연결  (0) 2024.03.14
v-if /v-for/ v-on event  (0) 2024.03.13
vue  (0) 2024.03.13
ECMA  (0) 2024.03.13