8000 Added section about using an argument · sdras/vuejs.org@b6b6697 · GitHub
[go: up one dir, main page]

Skip to content

Commit b6b6697

Browse files
committed
Added section about using an argument
1 parent f3a57b2 commit b6b6697

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/v2/cookbook/clickoutside-directive.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,3 +132,45 @@ Vue.directive('clickoutside', {
132132
}
133133
})
134134
```
135+
## Argument: Using different event types.
136+
137+
So far, your directive will only listen for `click` events. But there might be situations where we want to listen to other events, like `doubleclick` or `mousedown`.
138+
139+
For this, we can use an argument on our directive. This is what this looks like in our HTML:
140+
```html
141+
<modal v-clickoutside:dblclick="handler">
142+
143+
</modal>
144+
```
145+
146+
To use the argument in our directive, we only have to change the first argument of our `addEventListener()` and `removeEventListener()` calls to use the argument, if present:
147+
148+
```JavaScript
149+
bind(el, binding) {
150+
// ...
151+
const eventName = binding.arg || 'click'
152+
document.addEventListener(eventName, /*...*/)
153+
}
154+
155+
unbind(el, binding) {
156+
// ...
157+
const eventName = binding.arg || 'click'
158+
document.removeEventListener(eventName, /*...*/)
159+
}
160+
```
161+
162+
## Limitations
163+
164+
#### Doesn't work with v-show
165+
166+
`v-show` does not remove the element from the DOM, so `unbind()` is not triggered when `v-show` hides an element. This means that our clickoutside event is still active even if your modal is not visible, and would still fire for each click outside of the modal (which now, is basically *everywhere*)
167+
168+
#### No inline expressions
169+
170+
We can't use an inline expression instead of a handler function. The following will **not** work, because it will be run immediatly, not on `click`:
171+
172+
```html
173+
<modal v-clickoutside="showModal= false">
174+
175+
</modal>
176+
```

0 commit comments

Comments
 (0)
0