javascript - 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())
在组件中执行一个,我会得到未定义......
解决方案
看起来您的方法实际上从未返回任何内容。$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 值。
推荐阅读
- javascript - 如何使用cordova-plugin-filepath?
- python - 使用未按预期工作的关键参数按频率排序
- arrays - 如何替换字符串中的匹配字符?(红宝石)
- android - 如何最好地部署 Android 应用程序并允许更新
- javascript - 如何记录来自 fetch api 的响应
- java - 如何检查字符是否来自特定的字符集
- scala - 使用 H2 数据库时 Quill 中插入或更新操作的编译错误
- javascript - 检查字符串是否仅包含表情符号 - Javascript
- mysql - innodb 梭子鱼文件格式与希捷的关系
- javascript - 如何将 vue 数据绑定添加到动态创建的元素