首页 > 解决方案 > Vue.js - 自定义插件功能未定义

问题描述

我为我的 Vue2.js 项目创建了一个简单的插件,以获取表单中我的选择字段的一些列表。该插件应该进行一些 axios 调用并返回响应。

const ListSelector = {
  install (Vue){
    Vue.mixin({

      methods: {
        getSubscriberType: function() {
          this.$http
            .get('/web/admin/contract/subscribers')
            .then(function(response) { return response.data })
        },
//other methods (they do not work the same...)...
      }
    })
  }
}

export default ListSelector

我在 main.js 中注册了插件

import ListSelector from './backend/selectable'
Vue.use(ListSelector)

现在,如果我尝试在组件中调用插件方法,我会得到未定义的

<template>
...
<b-form-select v-model="form.type" :options="options" id="type" required></b-form-select>
...
</template>

<script>
export default {
data(){
  return {
    options: {}
  }
},
mounted(){
  this.options = this.getSubscriberType()
  }
}
<script>

我知道那this.getSubscriberType()是未定义的

编辑:我实际上看到该函数被触发(我在其中放置了一个警报......但如果我console.log(this.getSubscriberType())在组件中执行一个,我会得到未定义......

标签: javascriptvuejs2

解决方案


看起来您的方法实际上从未返回任何内容。$http.get()返回一个 Promise,而 Promise 本质上是异步的。

const ListSelector = {
  install (Vue){
    Vue.mixin({

      methods: {
        getSubscriberType: function() {
          this.$http
            .get('/web/admin/contract/subscribers') //returns a new promise
            .then(function(response) { //Executes after the promise resolves
                return response.data //not in the same scope as getSubscriberType
            })
            // getSubscriberType completes without a return value, hence undefined
        }
      }
    })
  }
}

因为函数在 promise 被解析之前解析,所以 getSubscriberType 甚至没有可用的响应。

相反,您想返回承诺。

        getSubscriberType: function() {
          return this.$http.get('/web/admin/contract/subscribers') // now returns promise
        }

然后,当响应完成时,您可以在本地对响应做任何您需要做的事情

var self = this // gives you a way to access local scope when the promise resolves

getSubscriberType().then(funciton(response) {
  self.subscriberType = response.data
})

在本例中,当 http 调用成功完成时,它将在组件上设置subscriberType 值。


推荐阅读