My method in vue looks like this :
methods: {
setDate: async function () {
console.log(this.modal)
}
}
I want to change it to an arrow function. I tried like this :
methods: {
setDate: async () => {
console.log(this.modal)
}
}
There exist error like this :
Cannot read property 'modal' of undefined
How can I solve this problem?
use function directly like
methods: {
async setDate() {
console.log(this.modal)
}
}
You are facing this error because an arrow function wouldn't bind this to the vue instance for which you are defining the method. The same would happen if you were to define computed properties using an arrow function.
Don’t use arrow functions on an instance property or callback e.g.
vm.$watch('a', newVal => this.myMethod())
As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.
You can read about it here.
This link https://michaelnthiessen.com/this-is-undefined/ says the following:
"An arrow function uses what is called lexical scoping. We'll get into this more in a bit, but it basically means that the arrow function takes this from it's context.
If you try to access this from inside of an arrow function that's on a Vue component, you'll get an error because this doesn't exist!
So in short, try to avoid using arrow functions on Vue components. It will save you a lot of headaches and confusion."
Related
Sup folks,
I have a lifecycle hook declared inside component like this:
export default {
created: function() {
console.log(this)
},
}
console prints vueComponent, all good.
However if I change it to an arrow function like so:
export default {
created: () => {
console.log(this)
},
}
now this is undefined.
Why? Thanks in advance for help.
The this keyword becomes unavailable in that scenario because arrow functions have no this context, so javascript looks in the outer scopes for that value. That means that if you use arrow functions, this will often be either undefined or take on an undesirable value.
That is also stated in the docs. Inside your Vue instances, avoid arrow functions.
It is already stated in the docs
from the docs
According to the page on event handling in the docs for Vue, when you use v-on like v-on:click="handler" the handler function will automatically get the original DOM event as the first argument. This code snippet is directly adapted from those docs.
new Vue({
// Vue config shortened for brevity
methods: {
handler(event) {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.name + '!')
// `event` is the native DOM event
if (event) {
alert(event.target.tagName)
}
}
}
})
Why the heck can I still access event even if I omit it from the functions parameter list like this:
handler() {
console.log(event); // Still returns the native DOM object even though
// I don't explicitly define `event` anywhere
}
Shouldn't event be undefined if I don't add it as an argument to the function?
I believe that'll be the global window.event:
https://developer.mozilla.org/en-US/docs/Web/API/Window/event
Nothing to do with Vue, it's just an unfortunate coincidence that you happened to call it event.
Maybe the docs explains the reason to use event in the handler function as first argument:
You should avoid using this property in new code, and should instead use the Event passed into the event handler function.
https://developer.mozilla.org/en-US/docs/Web/API/Window/event
Can any one guide or suggest how to resolve this below issue.
Use Case: Trying to implement notification component
Scenario: I am trying to call a method or change the state of the data on triggering of event in Vue.
I have defined the event listener on mounted function and trying to access one of the method.
Basically, the alert within event function is getting triggered, where as alert inside method is not getting triggered, and even any data manipulation is not executing even with in event function.
Where am i missing? is it incorrect to alter state within Event listener?
Basically i am trying to implement notification feature which automatically disappear after few seconds
Any help is appreciated.
Thanks,
Girish
There is another reason,this inside callback function is not Vue component. You can assign var self = this and use inside the callback, or use arrow function.
mounted: function () {
var self = this
EventBus.$on('show', function () {
self.test()
self.show = true
})
},
methods: {
test () {
console.log('Inside methods')
}
}
I believe your problem is the spelling error instead of
method: {}
, use methods: {}
Example:
Error.
method: {
test: function () {
alert('Inside Method');
}
correct.
methods: {
test: function () {
alert('inside method);
}
}
I know it does not have much to do with the question, but be careful when using the event bus, it would be as if you had a speaker, and shouted in the middle of a crowd the name of a person.
Example:
eventbus says Hamilton in the midst of a crowd of 10,000 people.
How many Hamiltons can you have in the middle of this crowd? Use something more specific, such as parent-child communication, avoid using the event bus.
I am trying to pass a function into recaptcha to be used as a callback. I need to write:
data-callback="function"
In Vue how do I add the function reference?
I've tried:
data-callback="{{ this.submitFocus }}"
data-callback="this.submitFocus"
I'm using Vue 2
Recaptcha2 uses the data-callback string to call a globally available function.
From what I can see in the documentation, it doesn't look like there's a programmatic way to set this so you might have to use something like this
beforeMount () {
window.submitFocus = () => { // using arrow function to preserve "this"
this.submitFocus()
}
},
beforeDestroy () {
delete window.submitFocus
}
with
data-callback="submitFocus"
in your template. The attribute value just needs to match the function added to window.
data-callback is an html attribute of a DOM element, it's just a string. It does not know about the context of your object instance, ie. this.
So, you can't use this when setting the attribute for your ReCaptcha, it will only understand functions that can be called without this.
If you had a function defined as
function submitFocus(){ ... }
globally, you could get ReCaptcha to call it by setting data-callback to submitFocus without the reference to this.
data-callback="submitFocus"
I have a button in a Vue component
<el-button class='range-right' #click='deleteItem(item)'>delete</el-button>
within it's handler I want to invoke other methods of the component.
however, even though I can call deleteItem which is itself a component method, I cannot get at the actual component for other methods.
is there a way to pass something like a $component param to the #click event?
methods {
deleteItem: (item, obj) => {
let api = '/api/train/deleteItem?_id=' + item._id
let resource = Vue.resource(api)
let vm = this // NOT a component
window.delItem = this
console.log('deleteItem.this', this)
resource.delete(api)
.then(items => {
console.log('deleted')
vm.methods.load() //<< fails
})
},
I think the problem is the arrow function as commented
See an example here using function:
https://jsfiddle.net/rvp6fvwp/
Arrow function is bound to the parent context as said here https://v2.vuejs.org/v2/guide/instance.html#Properties-and-Methods
Don’t use arrow functions on an instance property or callback (e.g.
vm.$watch('a', newVal => this.myMethod())). As arrow functions are
bound to the parent context, this will not be the Vue instance as
you’d expect and this.myMethod will be undefined.