我在VueJS中将feathersjsfeathers-client一起使用,并且出现Cannot set property 'employees' of undefined typeerror。这是我的代码:

<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


在控制台中。

我在这里做错什么了吗?

最佳答案

函数内部的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)
            })
       }
    }

09-28 00:56