基础/事件处理

63 阅读1分钟

事件处理器

<template>
  {{ count }}
  <!-- 会自动传递 event 参数 -->
  <button @click="handler"> +1 </button>
  
  <!-- 传参为空,handler获取的 e 为 undefined -->
  <button @click="handler()"> 不变 </button>
	
  <!-- 手动传递 event 参数 -->
  <button @click="handler($event)"> +1 </button>
	
  <!-- 手动传递 event 参数 -->
  <button @click="(e) => handler(e)"> +1 </button>
	
  <button @click="count++"> +1 </button>
</template>

<script setup>
  import { ref } from 'vue'

  const count = ref(0)
  
  const handler = (e) => {
    if (!e) return
    count.value++
  }
</script>

绑定多个事件处理器

通过数组来绑定多个事件处理器,注意数组里函数只能是函数调用,不能只写函数名称。并且是按照处理器在数组中的顺序来依次执行

<template>
  count: {{ count }}

  <button 
    @click="[
      handler1($event), 
      handler2($event, 1), 
      count++, 
      console.log('多个事件处理器执行结束')
    ]"
  >
    按钮
  </button>
</template>

<script setup>
  import { ref } from 'vue'

  const count = ref(0)

	const handler1 = (e) => {
    console.log(`第1个事件处理器执行,接收参数为:${e}`)
  }
  
  const handler2 = (e, index) => {
    console.log(`第${index + 1}个事件处理器执行,接收参数为:${e}`)
  }
</script>

如果多个事件处理器中存在异步

<template> 
  <button @click="[handler1(), handler2($event, 1)]"> 
    按钮 
  </button> 
</template> 

<script setup> 
import { ref } from 'vue'

const handler1 = () => {
  new Promise((resolve) => {
    setTimeout(() => {
      console.log(`第1个事件处理器执行`)
      resolve()
    }, 2000)
  })
}

const handler2 = (_, index) => {
  console.log(`第${index + 1}个事件处理器执行`) 
} 
</script>

控制台打印结果为:

第2个事件处理器执行
(两秒后打印) 第1个事件处理器执行

所以说绑定多个事件处理函数的时候,不会等待异步处理完成再执行下一个。

碰到第二个请求需要使用前一个请求的结果作为条件的情况,还是提前写好一个函数去处理,例如:

<template>
  <!-- @click="[request1(), request2()]" 这种写法无效,不能拿到结果。下面三种都可以按预期运行 -->
  <button @click="[handler()]">
    获取数据
  </button>
  <button @click="handler">
    获取数据
  </button>
  <button @click="handler()">
    获取数据
  </button>
 
  <p>
    {{ str }}
  </p>
</template>

<script setup>
  import { ref } from 'vue'
  
  const params = ref({})
  const str = ref('')
  
  function api1() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          id: 1,
          page: 1,
          pageSize: 10
        })
      }, 500)
    })
  }
  
  function api2({id = "给id一个默认值", page = "给page一个默认值", pageSize = "给pageSize一个默认值"}) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(`获取id为:${id},第 ${page} 页,每页 ${pageSize} 条`)
      }, 500)
    })
  }
  
  async function request1() {
    params.value = await api1()
  }
  
  async function request2() {
    str.value = await api2(params.value)
  }
  
  async function handler() {
    await request1()
    await request2()
  }
  
  // 一般都直接一个函数搞定
  async function foo() {
    params.value = await api1()
    str.value = await api2(params.value)
  }
</script>