Reputation: 131
I attempted to create a basic Vue directive, and had an issue accessing this
. I'm not using arrow functions in this case, and have taken an example straight from the Vue documentation, and am still experiencing this issue.
Reproducible: https://codesandbox.io/s/suspicious-lichterman-forud
Vue: v2.6.11
Directive:
// When bound produces `undefined` from console.log
// I've tried placing this in main.js / App.vue
Vue.directive("example", {
twoWay: true, // I've tried setting this false / true
bind: function() {
console.log(this);
},
unbind: function() {
console.log("unbind", this);
}
});
Upvotes: 3
Views: 1469
Reputation: 138276
You're referencing the v0.12
docs, but your example uses the current version of Vue (v2.6.11
). From the 2.x docs for bindings, the API for bind
is different:
Vue.directive('demo', {
bind: function (el, binding, vnode) {
var s = JSON.stringify
el.innerHTML =
'name: ' + s(binding.name) + '<br>' +
'value: ' + s(binding.value) + '<br>' +
'expression: ' + s(binding.expression) + '<br>' +
'argument: ' + s(binding.arg) + '<br>' +
'modifiers: ' + s(binding.modifiers) + '<br>' +
'vnode keys: ' + Object.keys(vnode).join(', ')
}
})
In 2.x, the data that was accessible through this
is now passed as hook arguments (i.e., el
, binding
, and vnode
). Also, twoWay
no longer exists in 2.x, as you could use Vue.set()
without specifying any props.
Upvotes: 1