如何在VueJS中的promise中设置数组对象属性的值?

时间:2017-03-01 00:06:41

标签: javascript html vue.js vuejs2 feathersjs

我正在使用feathersjsfeathers-client与VueJS,我得到Cannot set property 'employees' of undefined类型错误。这是我的代码:

<template>
  <ul>
    <li v-for="employee in employees">{{employee.name}}</li>
  </ul>
</template>

<script>
import feathers from 'feathers/client'
import socketio from 'feathers-socketio/client'
import hooks from 'feathers-hooks'
import io from 'socket.io-client'

const socket = io('localhost:3030')
var app = feathers().configure(hooks())
                    .configure(socketio(socket))
                    .configure(authentication({ storage: window.localStorage }));

export default {
 data() {
   return {
     employees: []
   }
 },
 mounted() {
     app.authenticate().then(function(response) {
          app.service('users').find().then(function(users) {
            this.employees = users.data
          })
        }, function(error) {
          console.log(error)
        })
   }
}

</script>

当我运行它时,我得到了

Uncaught (in promise) TypeError: Cannot set property 'employees' of undefined

在控制台中。

我在这里做错了吗?

1 个答案:

答案 0 :(得分:2)

函数内的

this指向该函数

 mounted() {
         var self = this; //add this line
         app.authenticate().then(function(response) {
              app.service('users').find().then(function(users) {
                self.employees = users.data //change this to self
              })
            }, function(error) {
              console.log(error)
            })
       }
    }