2017-11-23 11 views
0

Hello friends I am tired of getting this error when i count a length of notification by using vue.js and Laravel it show error,Uncaught (in promise) TypeError: Cannot read property 'forEach' of undefined plz help me. here is my code.catch되지 않은 (약속의) 형식 오류 : Laravel에 정의되지 않은 재산 '대해 forEach를'읽기 및

store.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) 
    }, 
} 
}) 

에게 vue.js 수 없습니다 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> 

web.php

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

그냥'을 console.log (무산자) 같은 REST 스타일의 접근 방식 '과 나던 것이 명백 할 것이다' –

+0

body' 난 빈 데이터를 가지고 –

+0

엡을 너무 그게 너에게 말하는거야? 서버에서 아무 것도 보내지 않았을 것입니다. 브라우저 콘솔의 네트워크 탭을 확인하고 전화가 무엇을 반환하는지 확인하십시오. –

답변

0

오류를 방지하려면 반환 값을 ma로 테스트해야합니다. 당신이 기대하는 모든 것이 있는지 확인하십시오.

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

오류는 없지만 제 수가 0입니다. –

+0

예. 그것은 또 다른 문제입니다. 왜 데이터가 돌아 오지 않는지 API를 통해 알아 내야 할 필요가 있습니다. – bbsimonbb

+0

답을 뒷받침하는 내용을 더 많이 제공하고 코드 스 니펫을 추가하는 것은 좋은 대답이 아닌 것 같습니다. – aloisdg

0

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에 밑줄을 사용하지 않는 것입니다. 예를 들어 Google은 밑줄로 구분 된 단어를 한 단어로 취급하지만 하이픈의 경우 두 단어로 간주합니다. get_unreadget-unread이어야합니다. 이것은 큰 문제는 아니지만, my_blog_title과 같은 다른 URL에 대해 이렇게하면 큰 문제가됩니다.

이 같은 통보를위한 더 나은 솔루션 http://mywebsite.com/user/notifications/unread

+0

all_nots_count : 0 이유는 무엇입니까? –

+0

서버에서 반환 된 데이터가 없기 때문에'forEach'를 시도 할 때 배열의 항목이 아닌'undefined'를 foreach하려고합니다. 이것이 실패하는 이유입니다. 이것은 vue 문제가 아니라 백엔드 문제입니다. 'dd (Auth :: user() -> unreadNotification)'을 시도해보십시오. (읽지 않은 상태 ** ** **) – Pistachio

+0

경로에 사용하고 있습니다. –