The Vue method is failing to properly send data to an array of objects

Trying to troubleshoot this issue is proving to be quite challenging for me. Despite following all the guidelines, I seem to be stuck at a roadblock and cannot figure out what is causing the problem.

Let's take a look at my vue.js application:

new Vue({
    name: 'o365-edit-modal-wrapper',
    el: '#o365-modal-edit-wrapper',
    data: function() {
        const default_apps = [
            {
                'post_title': 'Excel',
            }, {
                'post_title': 'Word',
            }, {
                'post_title': 'SharePoint',
        }];
        console.log(default_apps);

        const default_apps1 = this.get_array_of_post_objects('application_launcher');
        console.log(default_apps1);

        return {
            available_list: [],
            selected_list: default_apps.map(function(name, index) {
                return {
                    name: name.post_title,
                    order: index + 1,
                    fixed: false
                };
            }),
        }
    },
    methods: {
        get_array_of_post_objects(slug) {
            let items = [];
            wp.api.loadPromise.done(function () {
                const Posts = wp.api.models.Post.extend({
                    url: wpApiSettings.root + 'menus/v1/locations/' + slug,
                });
                const all_posts = new Posts();
                all_posts.fetch().then((posts) => {
                    items.push(...posts.items);
                });
            });
            return items;
        },
    },
    computed: {
        dragOptions() {
            // Additional <draggable> options for both lists.
            return {
                tag: 'div',
                group: 'o365apps',
                disabled: !this.editable,
                ghostClass: "ghost",
            };
        },
    },
});

Among my methods, there is one called get_array_of_post_objects, which returns an array of objects.

As part of the data section, I am logging two arrays - default_apps manually and default_apps1 utilizing the method. Both arrays contain objects with

post_title: "something"
.

The outcome I am observing is as follows: https://i.sstatic.net/9zAk8.png

When I use default_apps in my mapping, my IDE recognizes the result for name. However, when I switch to default_apps1, it fails to find any results as depicted in the following image:

I am unsure of where else to look for a solution - any assistance would be greatly appreciated!

If necessary, here is the accompanying HTML code:

<div class="column is-half-desktop is-full-mobile buttons">
    <nav class="level is-mobile mb-0">
        <div class="level-left">
            <div class="level-item is-size-5 has-text-left">Selected</div>
        </div>
        <div class="level-right">
            <div class="level-item" @click="orderList()"><i class="fas fa-sort-alpha-up is-clickable"></i></div>
        </div>
    </nav>
    <hr class="mt-1 mb-3">

    <draggable class="list-group"
               v-model="selected_list"
               v-bind="dragOptions"
               :move="onMove"
               @add="onAdd"
               @remove="onRemove"
               @start="isDragging=true"
               @end="isDragging=false">
        <button class="button is-fullwidth is-flex list-group-item o365_app_handle level is-mobile" v-for="(app, index) in selected_list" :key="app.order">
            <div class="level-left">
                <span class="icon" aria-hidden="true">
                    <img :src="`<?= Path::o365('${app.name}' . '.svg'); ?>'`" />
                </span>
                <span>{{app.name}}</span>
            </div>
            <div class="level-right is-hidden-desktop">
                <span class="icon has-text-danger is-clickable" @click="remove(index)">
                  <i class="fas fa-times"></i>
                </span>
            </div>
        </button>
    </draggable>
</div>

Answer №1

I'm not entirely certain about the purpose of your application, so make the necessary modifications to suit your requirements.

Initially, the selected_list will be empty. Subsequently, we invoke your asynchronous method, and once it completes, the selected_list will be populated.

new Vue({
  name: 'o365-edit-modal-wrapper',
  el: '#o365-modal-edit-wrapper',
  data: function() {
    return {
      available_list: [],
      selected_list: [],
    }
  },
  created() {
    this.get_array_of_post_objects("add-your-slug")
  },
  methods: {
    get_array_of_post_objects(slug) {
      wp.api.loadPromise.done(function() {
        const Posts = wp.api.models.Post.extend({
          url: wpApiSettings.root + 'menus/v1/locations/' + slug,
        });
        const all_posts = new Posts();

        all_posts.fetch().then((posts) => {
          // You might want to customize posts according to your requirements
          this.selectedList = posts
        });
      });
    },
  },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Copy both the image and JSON object to the clipboard

I am attempting to utilize the clipboard API to write an image and JSON object to the window clipboard. I am working with Vue and Electron and have successfully written an image and plain text, but I encounter an error when trying to write a JSON object: ...

Issue with form array patching causing value not to be set on material multiple select

When attempting to populate a mat-select with multiple options using an array of ids from Firestore, I encountered an issue. The approach involved looping through the array, creating a new form control for each id, and then adding it to the formArray using ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

What is the best approach to dynamically bind a style property in Vue.js 3?

I am currently working with vue3 and I am trying to apply dynamic styles. This is how my vue3 template looks: <ul> <li v-for="(question, q_index) in questions" :key="q_index" v-show="question.visible" :style="{ ...

Invert Three.js lookAt method with camera position

Currently, I am animating objects towards the camera and aiming to have them facing the camera upon arrival. To achieve this, I am utilizing object.lookAt(camera.position) However, I am encountering a challenge in tweeing the object back to its initial ro ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

Converting Strings to Booleans in Vue: A Dilemma

Within my Vue HTML code, I have the following: <v-textarea auto-grow="true"></v-textarea> The functionality works as intended, with the textarea expanding automatically. However, it does trigger an error message: [Vue warn]: Invalid ...

Having trouble showcasing information retrieved from API calls with v-for loop

I am trying to display all categories from the API using a v-for loop. When I use {{ categories }}, I can see all the information displayed, but when I try to access {{ categories.strCategory }}, I get a blank li element. Below is my code snippet: <u ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...

Transforming Text Using Random Characters Without Altering its Layout

What is a simple method to replace characters in a string while keeping the original format intact? For instance, if a string contains a phone number like 111-222-3333. My goal is to replace this number with a randomly generated one while maintaining the ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Please send the element that is specifically activated by the onClick function

This is the HTML code I am working with: <li class="custom-bottom-list"> <a onClick="upvote(this)"><i class="fa fa-thumbs-o-up"></i><span>upvote</span></a> </li> Here is my JavaScript function for Upvot ...

Flipping over every single card, but only desire to flip them one at a time

My attempt to flip these cards individually has resulted in them all flipping together. I suspect there may be an error in my JavaScript code. In the original code, I used images in front and an unordered list in the back, but here I have simplified it t ...

Angular loop is unable to detect changes in the updated list

My Angular application is facing a peculiar issue that I can't seem to figure out. // Here are the class attributes causing trouble tenants: any[] = []; @Input() onTenantListChange: EventEmitter<Tenant[]>; ngOnInit(): void { this. ...

What is the best method for executing computations within Vue.js 2?

Here is my second vue component: <template> <div class="row"> <div v-for="item in options"> <div class="panel panel-default panel-product"> .... </div> </div> ...

Populate a database with information collected from a dynamic form submission

I recently created a dynamic form where users can add multiple fields as needed. However, I'm facing a challenge when it comes to saving this data into the database. You can view a similar code snippet for my form here. <form id="addFields" me ...

The Intl.NumberFormat function does not support conversion to the pt-BR (Brazilian Portuguese) locale

A code sample is provided below: const formCurrency = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 }) Assuming the input is: var money = 1000.50 formCurrency.fo ...

Ways to verify whether the checkboxes within a gridview have been selected

enter code hereMy Gridview has five checkboxes in each row with options 'NO', 'YES', 'NA', 'NA/U', and 'REPEAT'. I am looking to enable a button if any of the checkboxes among 'NO', 'YES&apos ...

Managing multiple layouts in Nuxt.js when dealing with child pages - a comprehensive guide

Exploring the world of Nuxt.js and Vue.js for the first time has been an exciting journey. I am currently working on creating a template where I need to have two columns, with each column displaying different data. layouts/content.vue: <template> ...

What method is the most effective for preloading images and stylesheets?

One of the main concerns I have is optimizing the load time of my website. I would like to preload images, style sheets, and scripts to ensure a faster loading speed and to prevent users from seeing images loading right before them. Can someone suggest the ...