【问题标题】:Vue.js - Custom plugin function is undefinedVue.js - 自定义插件功能未定义
【发布时间】:2020-01-13 11:41:08
【问题描述】:

我为我的 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()),我会得到未定义...

【问题讨论】:

  • console.log(this.getSubscriberType) 没有括号会发生什么
  • 我得到类似函数 [{native code}]

标签: javascript vuejs2


【解决方案1】:

看起来您的方法实际上从未返回任何内容。 $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 值。

【讨论】:

  • 感谢它以这种方式工作,即使结果不如我想象的那么好,因为制作插件而不是直接在组件中调用 axios 并没有太多时间增益
猜你喜欢
  • 1970-01-01
  • 2018-10-23
  • 2018-03-14
  • 2021-06-20
  • 2022-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多