2017-03-01 106 views
1

我使用feathersjsfeathers-client与VueJS和我得到Cannot set property 'employees' of undefined typeerror。这是我的代码:如何在VueJS的promise中设置数组对象属性的值?

<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 

我在这里做错了什么?

回答

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) 
      }) 
     } 
    } 
+0

为什么我没有想到呢? – FewFlyBy

+0

@FewFlyBy¯\\ _(ツ)_/ – Traxo

+1

我确实想到了这一点,它使我发疯,我无法使它工作 –