I'm having a problem with a Vue JS. I'm looping over some "posts" from the WordPress Rest API, and I have to print the author of the post inside the v-for loop, for each post. The author assigned to a post, is only an ID, so I have to make a new call to the API, to get the author name based on the returned ID.
The issue i'm running into, is that when i call the function that's fetching the Author Name, it's constantly switching back and forth between all the users assigned to the posts in the posts object.
Vue.component('blog-posts', { props: { posts: {}, }, data() { return { userName: '', } }, template: ` <section class="entry" v-if="posts.length"> <div class="entry-content"> <article v-for="(post, index) in posts" :key="post.index"> <h1><a :href="post.link">{{ post.title.rendered }}</a></h1> <p v-html="post.content.rendered"></p> // THIS IS THE PROBLEM <p v-if="getAuthor(post.author)">{{ userName }}</p> <button type="submit" @click="deletePost(post)">Slet indlæg</button> </article> </div> </section> `, created() { // Of course it works if i put a constant user id in, but i need to parse in inside the loop. // this.getAuthor(2); }, computed: { }, methods: { deletePost: function(post) { let path = new wp.api.collections.Posts({ id: post.id }); Event.$emit('delete-post', path, post.id); }, getAuthor(author) { let vm = this; let user = new wp.api.models.User({ id: author, }); return user.fetch().then(response => { vm.userName = response.name; // return true; }); }, // showAuthor(author) { // let user = new wp.api.models.User({ // id: author // }); // user.fetch().then(response => { // this.userName = response.name; // // return true; // }); // }, }, }); const app = new Vue({ el: '#app', data: { wp: wp.api, message: 'Hello Vue', posts: [], }, mounted() { let posts = new wp.api.collections.Posts(); let response = posts.fetch().then(response => { this.posts = response; }); Event.$on('post-added', (item) => { this.posts.unshift(item.attributes); }); // Delete post Event.$on('delete-post', (item, id) => { this.posts.forEach((post, index) => { if ( post.id === id ) { this.posts.splice(index, 1); item.at(0).destroy(); } }); }); }, });I'm not entirely sure this is the best way to return the value of a function call.