未捕获(承诺中) TypeError:无法读取 Laravel & vue 中未定义的属性'forEach'.js



你好朋友们,当我使用 vue 计算通知长度时,我厌倦了出现此错误.js并且 Laravel 显示错误,未捕获(承诺) 类型错误:无法读取未定义的属性"forEach"请帮助我。 这是我的代码。

商店.js

import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)
export const store = new Vuex.Store({
state: {
nots: []
},
getters: {
all_nots(state) {
return state.nots
},
all_nots_count(state) {
return state.nots.length
},
},
mutations: {
add_not(state, not) {
state.nots.push(not)
},
}
})

UnreadNots.vue

<template>
<li>
<a href="/notifications">
Unread notifications
<span class="badge">{{ all_nots_count }}</span>
</a>
</li>
</template>
<script>
export default {
mounted() {
this.get_unread()
},
methods: {
get_unread() {
this.$http.get('/get_unread')
.then( (nots) => {
nots.body.forEach( (not) => {
this.$store.commit('add_not', not)
})
})
}
},
computed: {
all_nots_count() {
return this.$store.getters.all_nots_count
}
}
}
</script>

网络.php

Route::get('get_unread', function(){
return Auth::user()->unreadNotification;
});

为了避免此错误,您需要测试返回值以确保它具有您期望的所有内容。

if(nots && nots.body && nots.body.length){
nots.body.forEach( (not) => {
this.$store.commit('add_not', not)
})
}

您收到此错误是因为forEach需要一个数组。它是未定义的。从错误中可以清楚地看出这一点。

解决此问题的一种可能方法是检查nots.body是否为数组并且具有项。

this.$http.get('/get_unread')
.then(nots => {
if (Array.isArray(nots.body) && nots.body.length) {
nots.body.forEach(not => {
this.$store.commit('add_not', not)
})
}
})

另一个提示是不要在网址中使用下划线。例如,谷歌会将下划线分隔的单词视为一个单词,但对于连字符,他们会将其视为两个单词。get_unread应该是get-unread.这可能不是一个大问题,但如果你对其他网址(如my_blog_title)这样做,那么这是一个更大的问题。

对于此类通知,更好的解决方案是 REST 样式的方法,例如http://mywebsite.com/user/notifications/unread

不要使用 nots.body use nots.data。 5分钟前我遇到了同样的问题

最新更新