首页 > 解决方案 > vue.js 应用程序中的未定义方法不返回数据

问题描述

所以我有一个快速的问题,我想返回一些数据,但由于某种原因,我无法为我的方法获取任何数据。


所以我有以下componentvue.js应用程序:

Vue.component('favorites-edit-component', {
   template: `
   <div class="column is-half">
      <button class="button is-fullwidth is-danger is-outlined mb-0">
        <span>{{ name }}</span>
        <span class="icon is-small favorite-delete" v-on:click="$emit('remove')">
          <i class="fas fa-times"></i>
        </span>
      </button>
    </div>
   `,
    props: ['name'],
});

new Vue({
    el: '#favorites-modal-edit',
    data: {
        new_favorite_input: '',
        favorites: [],
        next_favorite_id: 6,
    },
    methods: {
        add_new_favorite: function() {
            this.favorites.push({
                id: this.next_favorite_id++,
                name: this.new_favorite_input
            })
            this.new_favorite_input = ''
        },
        get_favorite_menu_items: function() {
            wp.api.loadPromise.done(function () {
                const menus = wp.api.collections.Posts.extend({
                    url: wpApiSettings.root + 'menus/v1/locations/favorites_launcher',
                })
                const Menus = new menus();
                Menus.fetch().then(posts => {
                    const test = posts.items.map(item => {
                        const items = {};
                        items['id'] = item.ID;
                        items['name'] = item.post_title;

                        console.log(items);
                    });
                });
            })
        }
    },
    created () {
        // fetch the data when the view is created
        console.log(this.get_favorite_menu_items());
        this.get_favorite_menu_items();
    },
});

所以我希望能够从方法中提取数据get_favorite_menu_items并将其传递给favorites: [].

现在,在created ()通话中,我得到undefinedthis.get_favorite_menu_items();.


在我的方法中,当 I 时console.log(items);,我得到以下返回: 在此处输入图像描述

它正在复制我的对象,这不是我想要的。所以这就是我想要做的:

  1. 从方法中获取对象(应该只有两个)。
  2. 在数组中构建对象,然后将数组传递给favorites: [].

当我console.log(test)这部分时,我得到以下回报[undefined, undefined], [undefined, undefined]

Menus.fetch().then(posts => {
    // this.favorites = posts.items;
    const test = posts.items.map(item => {
        const items = {};
        items['id'] = item.ID;
        items['name'] = item.post_title;
    });
    console.log(test);
});

所有帮助将不胜感激!

标签: javascriptarraysvue.jsvuejs2vue-component

解决方案


在你的map你没有返回任何价值 - 试试这个:

this.favorites = posts.items.map(item => {
  const items = {};
  items['id'] = item.ID;
  items['name'] = item.post_title;
  return items;
});

推荐阅读