VueJS: why is this undefined?
Both of those examples use an arrow function () => { }
, which binds this
to a context different from the Vue instance.
As per the documentation:
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 andthis.myMethod
will be undefined.
In order to get the correct reference to this
as the Vue instance, use a regular function:
mounted: function () {
console.log(this);
}
Alternatively, you can also use the ECMAScript 5 shorthand for a function:
mounted() {
console.log(this);
}
VueJS - this is undefined in common function
In this situation I recommend to define eventable
as a mixin :
const eventable= {
methods: {
goToEvent(event, upcoming=false) {
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
}
export default eventable;
in your vue file :
import eventable from "@/eventable";
export default {
name: "update",
mixins:[eventable],
....
second solution :
export an object with the function as nested method then import it and spread it inside the methods
option :
export default {
goToEvent(event, upcoming=false){
this.$store.dispatch({
type: 'setEventsDay',
day: event.start_date
})
}
}
then :
import goToEvent from "@/common";
export default {
name: "update",
methods: {
...goToEvent,
otherMethod(){},
}
//....
}
How can i fix “this is undefined” in VueJS?
In the callback context, this
tense to callback itself. That's why you are getting the error. You should replace it with,
self.$store.commit('disconnect');
where the self
holds the actual context of Vue. Here is the explanation,
methods: {
async login() {
var self = this; // You got the context of the method which belongs to Vue
const auth_res = axios({
method:'post',
...
}).then(function(res){
self.$store.commit('disconnect'); // The self.$store is now avaialable in callback
self.$router.push('/');
}).catch(function (erreur) {
...
});
}
}
Why do I get Undefined error when trying to pass async API data as prop from parent to child component?
v-bind="post"
The child prop is named "post", but the parent is trying to bind several properties with v-bind="post"
.
The binding name should match the target prop in the child:
<!-- <PostEditor v-bind="post" /> --> ❌ binds subproperties of post
<PostEditor v-bind:post="post" /> ✅ binds post
<PostEditor :post="post" /> ✅ binds post (shorthand)
post
default prop value
The child's post
prop has a default
option of () => {}
, but that arrow function returns nothing (undefined
), as the curly brackets start a block scope. This is effectively the same as not having the default
option.
You likely meant for default
to return an empty object, which requires wrapping the curly braces in parentheses:
// default: () => {} // ❌ returns undefined
default: () => ({}) // ✅ returns {}
data()
not reactive
Even with the prop default fixed above, the formValues.title
property in data()
is initialized to this.post.title
, which would be undefined
because post
is initially an empty object. The post
value passed in from the parent is updated asynchronously, so the value is still the initial value from the parent (also an empty object) in data()
.
Note that data()
is not reactive, so it's only called once at initialization. Changes to this.post
will not automatically update the data property.
Solution: Render child after post
populated
One solution is to defer rendering the child component until the post
prop is populated in the parent so that the post
prop would have the expected values for the child's data()
initialization.
In the parent, initialize post
to null
, and use v-if="post"
to conditionally render the child:
<template>
<div> br> <PostEditor :post="post" v-if="post" />
</div>
</template>
<script>
export default {
data() {
return { br> post: null,
}
},
}
</script>
demo
Vue JS - Helper Async Await function to fetch data returning undefined
you got a few errors in your code here are the solutions:
component.vue
import { currentDateTime , fetchUserData } from '@/helpers/util.js';
export default {
data () {
return {
userData: null,
loaded: false
}
},
methods : {
currentDateTime , fetchUserData ,
async setData () {
const { data } = await fetchUserData(123);
this.loaded = true
this.userData.name = data.name
}
},
created() {
this.setData()
}
}
util.js
import axios from 'axios';
export async function fetchUserData(id) {
try {
const response = await axios.get('/data-table/' + id);
return response;
} catch (e) {
throw e;
}
}
Vue.js undefined error on object value when loaded and rendered
When your component renders it tries to get value from job.location.name
but location
is undefined before ajax request is completed. So I guess error is kind of Cannot read property 'name' of undefined
.
To fix this you can define computed
property locationName
and return, for example, empty string when there is no loaded job object yet:
computed:{
//...
locationName() {
return this.job.location ? this.job.location.name : '';
}
}
Or you can define computed for location
and return empty object if there is no location, or you can just add empty location object to your initial data(if you are sure that your API response always has location
) like job: { location: {}}
all ways will fix your issue.
Also there is a way to fix it with v-if
directive in your template:
<div v-if="job.location">
{{ job.location.name }}
<!-- other location related stuff -->
</div>
Related Topics
JavaScript: Difference Between .Foreach() and .Map()
Jspdf Can't Get Any Styling to Work
Am I Using Too Much Jquery? When am I Crossing the Line
How to Write a Countdown Timer in JavaScript
JavaScript Inheritance and the Constructor Property
Sleep in JavaScript - Delay Between Actions
Persistent Service Worker in Chrome Extension
How to Simulate a Click With JavaScript
Jquery Scroll() Detect When User Stops Scrolling
How to Update the Parent'S State in React
Response to Preflight Request Doesn't Pass Access Control Check
Arrow Function Without Curly Braces
How to Fix Client_Missing_Intents Error
How to Concatenate and Minify Multiple CSS and JavaScript Files with Grunt.Js (0.3.X)
How to Detect My Browser Version and Operating System Using JavaScript