Javascript vue.js应用程序中未定义的方法不返回任何数据
所以我有一个简单的问题,我想返回一些数据,但由于某种原因,我无法向我的方法获取任何数据Javascript vue.js应用程序中未定义的方法不返回任何数据,javascript,arrays,vue.js,vuejs2,vue-component,Javascript,Arrays,Vue.js,Vuejs2,Vue 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&
因此,我有以下
组件
和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();
},
});
所有的帮助将不胜感激 在您的
映射中
没有返回任何值-请尝试以下操作:
this.favorites = posts.items.map(item => {
const items = {};
items['id'] = item.ID;
items['name'] = item.post_title;
return items;
});
从我看到的情况来看,您没有从get_favorite_menu_items返回任何值。@ThomasBay,我试图
返回$items
甚至this.favorite=items
,但仍然没有得到任何结果。我想您看到重复结果的原因是您调用了this.get_favorite_menu_items()
从创建的中创建两次
——一次在控制台中。记录
,一次由自己完成。嘿,汉娜,非常感谢!现在当我console.log(this.favorite)
outsidethis.favorites=posts…
我有一个对象数组的单个输出!求爱。第二个问题似乎是created()
方法仍在返回未定义的结果。不用担心!你可以让你的created
方法async
例如async created(){等待这个。获取你最喜欢的菜单项()}
但是由于这个方法没有返回任何东西,你仍然会得到一个未定义的结果。但是如果你console.log(this.favorites)
在那一行之后,我认为它应该可以工作。这就是你想要在这里实现的吗?抱歉,我应该补充一点-你还需要将这个.get\u favorite\u menu\u items()
作为一个异步函数。所以我将它转换为异步get\u favorite\u menu\u items(){
然后我转换为console.log(这个.favorites)
在created()。
this.favorites = posts.items.map(item => {
const items = {};
items['id'] = item.ID;
items['name'] = item.post_title;
return items;
});