Php 未捕获(承诺中)类型错误:无法读取属性';forEach&x27;在Laravel&;vue.js
朋友们好,当我使用vue.js和Laravel计算通知的长度时,我已经厌倦了这个错误,它显示错误,未捕获(承诺中)类型错误:无法读取未定义plz help me的属性“forEach”。这是我的密码 store.jsPhp 未捕获(承诺中)类型错误:无法读取属性';forEach&x27;在Laravel&;vue.js,php,laravel,vue.js,pusher,Php,Laravel,Vue.js,Pusher,朋友们好,当我使用vue.js和Laravel计算通知的长度时,我已经厌倦了这个错误,它显示错误,未捕获(承诺中)类型错误:无法读取未定义plz help me的属性“forEach”。这是我的密码 store.js import Vuex from 'vuex' import Vue from 'vue' Vue.use(Vuex) export const store = new Vuex.Store({ state: { nots: [] }, getters: {
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)
},
}
})
未读的
<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>
为了避免错误,您需要测试返回值,以确保它包含您期望的所有内容
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)
})
}
})
另一个技巧是不要在URL中使用下划线。例如,谷歌将用下划线分隔的单词作为一个单词,但对于连字符,他们会考虑两个单词。code>get_unread应该是get unread
。这可能不是一个大问题,但如果您对其他URL(如my_blog\u title
)这样做,那么这将是一个更大的问题
对于这样的通知,更好的解决方案是REST风格的方法,如
http://mywebsite.com/user/notifications/unread
不要使用nots.body使用nots.data。
5分钟前我也有同样的问题,只是
console.log(nots)
,很明显,它没有body
我得到了空白数据Yeap,那告诉你什么?可能没有从您的服务器发送任何内容。检查浏览器控制台中的“网络”选项卡,查看呼叫返回的内容请提供一个屏幕截图,显示从/get\u unread
返回的内容。您可以在浏览器或邮递员中打开它。所有不计数:0为什么是这样?因为您没有从服务器返回任何数据,所以当它尝试对它们进行forEach
时,它们尝试对数组中的任何项进行forEach未定义的
操作。这就是它失败的原因。这不是vue问题,而是后端的问题。试试dd(Auth::user()->unreadNotification)
(确定它不是unreadNotifications?)我在Route中有使用我不明白你在说什么,或者你是否理解我在web.php中所说的,就像return Auth::user()->unreadNotifications一样;当然这是另一个问题。你需要在你的api中搜索,看看为什么没有数据返回。提供更多的内容来支持你的答案,仅仅添加一个代码片段似乎不是一个好的答案。
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)
})
}
})