$dispatch

클릭시 함수 실행하기 :: $dispatch() 와 @함수=""

$dispatch 는 @정의된 함수만 실행됨..
@click 은 외부 함수만 실행됨..
@say="sayHell", @say="sayHell()" 동일한 내용이다.
1 
2 // $dispatch() 가 필요한 이유는?
3 
4<div x-data="{
5 toggle() { alert('toggle')},
6 }" @say="sayHello()" @notice="sayHello" @test="alert('test')" @dotoggle="toggle">
7 
8 
9 <h3>@click 이벤트는 외부 함수만 실행한다.</h3>
10 <button @click="say">say 동작안함</button><br>
11 <button @click="sayHello">sayHello 동작함</button><br>
12 <button @click="tellme">tell me 동작함</button><br>
13 
14 
15 <hr class="my-4">
16 
17 <h3>$dispatch 는 내부함수만 동작시킨다.</h3>
18 
19 <button @click="$dispatch('say')">say 동작함</button><br>
20 <button @click="$dispatch('notice')">notice 동작함</button><br>
21 <button @click="$dispatch('sayHello')">sayHello 동작안함</button><br>
22 <button @click="$dispatch('sayHello()')">sayHello() 동작안함</button><br>
23 
24 <hr class="my-4">
25 
26 <h3>sayHello, sayHello() 비교</h3>
27 
28 <button @click="$dispatch('say')">@click="$dispatch('say')" 동작함</button><br>
29 <button @click="$dispatch('notice')">@click="$dispatch('notice')" 동작함</button><br>
30 
31 <hr class="my-4">
32 
33 <h3>x-data 에서 정의한 함수 toggle</h3>
34 
35 <button @click="toggle">@click="toggle" 동작함</button><br>
36 
37 <button @click="$dispatch('toggle')">$dispatch('toggle') 동작안함</button><br>
38 
39 
40 <hr class="my-4">
41 
42 <h3>@로 직접 함수정의</h3>
43 
44 <button @click="test">@click="testfun"</button><br>
45 <button @click="test()">@click="testfun()"</button><br>
46 <button @click="$dispatch('test')">@click="$dispatch('test')"</button>
47 
48 
49 <hr class="my-4">
50 
51 <h3>x-data 에서 정의된 함수 $dispatch 실행하기</h3>
52 <button @click="$dispatch('dotoggle')">dotoggle</button>
53 
54 </div>
55 
56 <script>
57 function sayHello()
58 {
59 alert('Say Hello!!');
60 }
61 
62 function tellme()
63 {
64 alert('tell me');
65 }
66 </script>

@click 이벤트는 외부 함수만 실행한다.





$dispatch 는 내부함수만 동작시킨다.






sayHello, sayHello() 비교




x-data 에서 정의한 함수 toggle




@로 직접 함수정의




x-data 에서 정의된 함수 $dispatch 실행하기


매개변수 전달하기

클릭시 데이타 전달방법

1<div x-data="{}" @senddata="openAlertDetail($event.detail.stockid)">
2 <button @click="$dispatch('senddata',{ stockid : 'C33333'})">클릭하기</button>
3</div>
4 
5<script>
6 function openAlertDetail(id)
7 {
8 alert(id);
9 }
10</script>

별도의 태그에 정의하는 경우..window 를 사용함.

1 <div x-data="{}" @senddata="openAlert($event.detail.stockid)">
2 <button @click="$dispatch('senddata',{ stockid : 'C33333'})">클릭하기</button>
3 </div>
4 
5 <script>
6 function openAlert(id)
7 {
8 alert(id);
9 }
10 </script>
...

test

1<div x-data="{ title: 'Hello'}" @set-title.window="title = $event.detail" @set-title="title = $event.detail">
2 
3 <h1 x-text="title"></h1>
4 <button @click="$dispatch('set-title','Philip Hi')">Click Me1</button>
5 
6</div>
7 
8<div x-data>
9 <button @click="$dispatch('set-title','Hello World')">Click Me2</button>
10</div>