I've got an error when tried to declare a variable in the usual way like this:
Vue.directive('my-directive', {
varA: '',
inserted: function(el, binding, vnode){
this.varA = 'test'; // TypeError: Cannot set property
// 'varA ' of undefined
},
});
TypeError: Cannot set property 'varA ' of undefined
How do you declare variables in Vue directives?
Vue. js comes pre-packaged with a number of directives that developers commonly use when working within the framework. Directives such as v-if , v-show , v-on , v-model , v-bind , v-html , and more are all provided for you out-of-the-box. All of these provided directives start with v- .
Directives are used to modify the behavior of our HTML elements which reside in the DOM. In other words, we can say that directives are one of the important parts of the Vue and it is used just like an HTML element's attribute added along with any HTML elements into the Vue template.
To register a custom directive locally, navigate to the component where you want to use the custom directive, and add the method below as part of the Vue Options API: … directives: { focus: { // directive definition inserted: function (el) { el. focus() } } } ...
In Vue directives, when you need to store a value it is generally stored on the element.
Vue.directive('my-directive', {
inserted: function(el, binding, vnode){
el.varA = 'test';
},
});
The element is passed in as an argument to each of the lifecycle events in a directive and you can access the value later from el.varA
.
There seems to be 2 ways for this:
According to this comment on github, you may define a stateful directive like this:
Vue.directive('my-directive', (() => {
let varA = '';
return {
inserted: function(el, binding, vnode){
varA = 'test';
},
};
})());
According to a note box on Vue.js docs:
If you need to share information across hooks, it is recommended to do so through element’s dataset.
Vue.directive('my-directive', {
inserted: function(el, binding, vnode){
el.dataset.varA = 'test';
},
});
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