I'm trying to set the data()
value in a Vue
instance to a value retrieved from a Promise that is returned from a mongodb api
call. I'm able to retrieve the data I'm trying to implement, however am struggling to use it in the data()
field so that I can access it in the template.
Some of the solutions I've found from vue2
don't seem to work in this instance. Thanks in advance.
Vue
<template>
<Article :title=posts[0].title></Article> // Another Vue component
</template>
let stories;
export default {
data() {
return {
posts: {}
}
},
methods: {
loadPosts() {
stories = getPosts(); // makes an api request to a mongodb that returns a Promise
stories.then(function(response) {
this.posts = response.posts;
console.log(response.posts[0].title); // "My Post Title"
});
}
},
mounted() {
this.loadPosts();
}
}
The error I receive says
Uncaught (in promise) TypeError: Cannot set property 'posts' of undefined
in reference to this.posts = ...
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!
If we want to bind any variable, we can simply use Vue. js's double curly braces syntax or “Mustache” syntax to bind any variable from the relative component instance. Or, if we want to bind any variable inside an HTML attribute, we can use the v-bind directive.
this
get the window
reference as you are using dynamic
scope, use lexical scope binding
to get this
as Vue
For your specific reference and eagerness to read more about scopes - follow this Static (Lexical) Scoping vs Dynamic Scoping (Pseudocode)
For lexically binding use arrow-function
loadPosts() {
stories = getPosts();
stories.then(response => {
this.posts = response.posts;
console.log(response.posts[0].title); // "My Post Title"
});
}
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