javascript - vue.js 应用程序中的未定义方法不返回数据
问题描述
所以我有一个快速的问题,我想返回一些数据,但由于某种原因,我无法为我的方法获取任何数据。
所以我有以下component
和vue.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 ()
通话中,我得到undefined
了this.get_favorite_menu_items();
.
在我的方法中,当 I 时console.log(items);
,我得到以下返回:
它正在复制我的对象,这不是我想要的。所以这就是我想要做的:
- 从方法中获取对象(应该只有两个)。
- 在数组中构建对象,然后将数组传递给
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);
});
所有帮助将不胜感激!
解决方案
在你的map
你没有返回任何价值 - 试试这个:
this.favorites = posts.items.map(item => {
const items = {};
items['id'] = item.ID;
items['name'] = item.post_title;
return items;
});
推荐阅读
- typescript - Typescript async/await 无法确定正确的返回类型
- java - Java并发编程中的“同步”一词与同步/异步中的同步有什么关系?
- php - 在两个 PHP 版本之间切换
- python - Keras 似乎忽略了我的 batch_size 并尝试将所有数据放入 GPU 内存中
- c++ - 为 C++ 编程和开发配置 VS 代码
- hive - 列“ex:x 属于字符串类型”的 Parquet 模式不兼容 列类型:STRING、Parquet 模式
- python - 如何将列表列表转换为网格格式的单个字符串?
- python - 找到最大加权子集,使得子集中的任何两个元素总和不等于 k
- azure - 是否可以在工作区上过滤 OMS 仪表板?
- windows - 无法更改服务启动模式