事件处理
<h4>内联事件处理器:</h4>
<pre><code class="language-javascript">&lt;button @click=&quot;num++&quot;&gt;点击&lt;/button&gt;
let num = ref(1)</code></pre>
<hr />
<h4>方法事件处理器:</h4>
<pre><code class="language-javascript">&lt;button @click=&quot;btnclick&quot;&gt;点击&lt;/button&gt;
let num = ref(1)
const btnclick = () =&gt; {
num.value++
}</code></pre>
<p>默认传入 event 参数:</p>
<pre><code class="language-javascript">&lt;button @click=&quot;btnclick&quot;&gt;点击&lt;/button&gt;
const btnclick = (e) =&gt; {
console.log(e)
}</code></pre>
<p>如果想传多参数,event参数要写 $event:</p>
<pre><code class="language-javascript">&lt;button @click=&quot;btnclick('Andy',$event)&quot;&gt;点击&lt;/button&gt;
const btnclick = (name, e) =&gt; {
console.log(name)
console.log(e)
}</code></pre>
<hr />
<h4>鼠标按键修饰符:</h4>
<pre><code class="language-javascript">&lt;div class=&quot;red&quot; @click.left=&quot;redLeftClick&quot; @click.right=&quot;redRightClick&quot; @click.middle=&quot;redMiddleClick&quot;&gt;
&lt;div class=&quot;blue&quot; @click.left=&quot;blueLeftClick&quot; @click.right=&quot;blueRightClick&quot; @click.middle=&quot;blueMiddleClick&quot;&gt;&lt;/div&gt;
&lt;/div&gt;
const redLeftClick = () =&gt; {
console.log('redLeftClick')
}
const blueLeftClick = () =&gt; {
console.log('blueLeftClick')
}
const redRightClick = () =&gt; {
console.log('redRightClick')
}
const blueRightClick = () =&gt; {
console.log('blueRightClick')
}
const redMiddleClick = () =&gt; {
console.log('redMiddleClick')
}
const blueMiddleClick = () =&gt; {
console.log('blueMiddleClick')
}</code></pre>
<p><img src="https://www.showdoc.com.cn/server/api/attachment/visitFile?sign=52c8899dfd0ab53395f7439a86cab52d&amp;file=file.png" alt="" />
遵循冒泡原则</p>
<hr />
<h4>事件修饰符:</h4>
<p>.stop</p>
<pre><code class="language-javascript">//阻止冒泡,执行到 blueClick 就结束了
&lt;div class=&quot;red&quot; @click=&quot;redClick&quot;&gt;
&lt;div class=&quot;blue&quot; @click.stop=&quot;blueClick&quot;&gt;&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>.self</p>
<pre><code class="language-javascript">//当前元素本身被点击事件时才执行
&lt;div class=&quot;red&quot; @click.self=&quot;redClick&quot;&gt;
&lt;div class=&quot;blue&quot; @click=&quot;blueClick&quot;&gt;&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>.once</p>
<pre><code class="language-javascript">//当前元素只被调用一次,listener 会在被调用之后移除
&lt;div class=&quot;red&quot; @click=&quot;redClick&quot;&gt;
&lt;div class=&quot;blue&quot; @click.once=&quot;blueClick&quot;&gt;&lt;/div&gt;
&lt;/div&gt;</code></pre>
<p>.capture</p>
<pre><code class="language-javascript">//事件捕获,先捕获再冒泡,先执行redClick,再执行blueClick
&lt;div class=&quot;red&quot;&gt;
&lt;div class=&quot;blue&quot; @click=&quot;blueClick&quot; @click.capture=&quot;redClick&quot;&gt;&lt;/div&gt;
&lt;/div&gt;</code></pre>
<hr />
<h4>键盘按键修饰符:</h4>
<pre><code class="language-javascript">&lt;input @keydown=&quot;btnclick&quot; @keyup=&quot;btnclick&quot; /&gt;
const btnclick = (e) =&gt; {
console.log(e)
}</code></pre>