Vue - 无法在promise中设置undefined的属性

Pho*_*rce 9 javascript vue.js

所以我有以下Vue文件:

<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>
Run Code Online (Sandbox Code Playgroud)

这是编译得很好,但是,在加载网页时,我收到以下错误:

app.js:1769未捕获(在承诺中)TypeError:无法设置未定义的属性'message'

我也试图创造另一种方法,但没有快乐.我似乎无法解决为什么this不能在这里访问.

Cob*_*way 40

您的上下文正在发生变化:因为您使用的是关键字函数,this所以在其范围内是匿名函数,而不是vue实例.

请改用箭头功能.

  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);
        });

    },
Run Code Online (Sandbox Code Playgroud)

注意:顺便说一下,你应该继续使用关键字函数作为方法的顶层(如示例所示),因为否则Vue无法将vue实例绑定到this.

  • 观察者在VueJS中是正常的东西,它们附加到数据对象中的每个属性,这是vuejs跟踪更改并立即更新它们的一种方式@Phorce建议使用Vue Devtools chrome扩展 (2认同)

ses*_*ith 7

可以将其设置thisconst代码块外部并使用该 const 值来访问类属性。

IE

const self = this;

blockMethod(function(data) {
    self.prop = data.val();
})
Run Code Online (Sandbox Code Playgroud)