I currently have something like this:
<q-input v-model="value" label="Some Label" v-bind="getDefaults('someId')" />
where getDefaults() is:
function getDefaults (id) {
return {
'id': id,
'clearable': true,
'lazy-rules': true,
'outlined': true,
'class': 'form-padding'
// more props/parameters
}
}
Now, I want to convert the v-bind to a custom directive.
export const sampleDirective = {
inserted: function (el, binding) {
// this doesn't work
el.class += 'form-padding'
// how to set id from here
// and how to set the props as well (like ```clearable```, ```lazy-rules```, etc)?
}
}
So how can I set these parameters/props from the custom directive so I can just call it like this:
<q-input v-model="value" label="Some Label" v-sampleDirective="{ id: 'someId' }" />
Thanks!
According to documentation
Note that in Vue 2.0, the primary form of code reuse and abstraction is components - however there may be cases where you need some low-level DOM access on plain elements, and this is where custom directives would still be useful.
So one thing is clear, props are out of the question; you have to use default provided directives like v-bind as you cant access/change anything other than raw DOM element. the default provided directive works something different and at compiling the component to render function; where as custom directive works different and only allow to modify DOM element.
to be more clear directives like v-if, v-else are used in template converted to javascript if-else clause in render function where simillarly v-for converted to for loop in render function.
As the question of class, id and Other attributes of a DOM element you can modify those using native javascript DOM APIs like element.classList.add("my-class"), or element.setAttribute('id', 'something') etc.
Note: My personal opinion about naming custom directive leading to the confusion of some peoples including myself that custom directive are equivalent to vue's directives like v-for and can be constructed by API user, which is not the case.
TL DR;
Well you cant!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With