Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue - Cannot set property of undefined in promise

So I have the following Vue file:

<template>

  <li class="notifications new">
      <a href="" data-toggle="dropdown"> <i class="fa fa-bell-o"></i> <sup>
          <span class="counter">0</span>
          </sup>
       </a>
       <div class="dropdown-menu notifications-dropdown-menu animated flipInX">
            <ul v-for="notification in notifications" @click="" class="notifications-container">
              <li>
                <div class="img-col">
                  <div class="img" style="background-image: url('assets/faces/3.jpg')"></div>
                </div>
              </li>
            </ul>
        </div>
  </li>

</template>

<script>
export default {

    data: function() {
        return {
          notifications: [],
          message: "",
        }
    },

    methods: {

        loadData: function() {
            Vue.http.get('/notifications').then(function(response) {

                console.log(response.data);
                //this.notifications = response.data;
                //this.notifications.push(response.data);

                this.message = "This is a message";

                console.log(this.message);
            });

        },
    },

    mounted() {
        this.loadData();
    },

}

</script>

This is compiling just fine, however, when loading up the web page, I get the following error:

app.js:1769 Uncaught (in promise) TypeError: Cannot set property 'message' of undefined

I have tried to create another method as well, but had no joy. I literally cannot seem to work out why this wouldn't be accessible here.

like image 753
Phorce Avatar asked Apr 25 '17 14:04

Phorce


1 Answers

Your context is changing: because you are using the keyword function, this is inside its scope the anonymous function, not the vue instance.

Use arrow function instead.

  loadData: function() {
        Vue.http.get('/notifications').then((response) => {

            console.log(response.data);
            //this.notifications = response.data;
            //this.notifications.push(response.data);

            this.message = "This is a message";

            console.log(this.message);
        });

    },

NB: You should by the way continue to use the keyword function for the top level of your methods (as shown in the example), because otherwise Vue can't bind the vue instance to this.

like image 138
FitzFish Avatar answered Nov 04 '22 04:11

FitzFish