vue3 自定义指令怎么获取事件的传参
时间: 2023-10-19 16:17:47 浏览: 234
在 Vue3 中,自定义指令可以通过第二个参数 `binding` 来获取事件的传参,具体步骤如下:
1. 在自定义指令的 `mounted` 或 `updated` 钩子函数中,通过 `binding.value` 来获取事件的传参。
2. 如果希望在事件回调函数中获取传参,可以将传参通过 `binding.value` 保存到指令绑定的元素上,然后在事件回调函数中通过 `event.target.value` 来获取传参。
以下是一个示例代码:
```javascript
import { Directive, DirectiveBinding } from 'vue'
const customDirective: Directive = {
mounted(el: HTMLElement, binding: DirectiveBinding) {
// 获取事件的传参
const arg = binding.value
// 将传参保存到元素上
el.setAttribute('arg', arg)
// 绑定事件回调函数
el.addEventListener('click', (event: MouseEvent) => {
// 获取传参
const arg = event.target.getAttribute('arg')
// 执行事件回调函数
console.log(arg)
})
}
}
export default customDirective
```
在上面的示例中,我们首先通过 `binding.value` 获取事件的传参,并将传参保存到元素上。然后在事件回调函数中,通过 `event.target.getAttribute('arg')` 获取传参,并执行相应的逻辑。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)