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

标签 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

在控制台中。

我是不是做错了什么?

最佳答案

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

关于javascript - 如何在 VueJS 的 promise 中设置数组对象属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42520977/

相关文章:

javascript - 为什么这个代码是有效的?

javascript - 在特定滚动位置激事件画

sockets - Quasar 应用程序路由问题

javascript - 如何从字符串中删除一个字符

javascript - 如何在 javascript 中创建是/否/取消框而不是确定/取消?

html - md-button 调整字体大小以适合按钮大小

javascript - 多个复选框过滤器返回服务器错误 500

javascript - 在Vue客户端和服务器应用程序中如何消除对CORS的需要?

javascript - Electron Js应用程序菜单单击可多次运行

javascript - 在 IE 10 浏览器中,链接按钮出现错误 __dopostback is undefined