Javascript Vue.js-自定义插件函数未定义
我已经为我的Vue2.js项目创建了一个简单的插件,以获取表单中我的选择字段的一些列表。插件应该进行一些axios调用并返回响应Javascript Vue.js-自定义插件函数未定义,javascript,vuejs2,Javascript,Vuejs2,我已经为我的Vue2.js项目创建了一个简单的插件,以获取表单中我的选择字段的一些列表。插件应该进行一些axios调用并返回响应 const ListSelector = { install (Vue){ Vue.mixin({ methods: { getSubscriberType: function() { this.$http .get('/web/admin/contract/subscribers'
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)
现在,如果我尝试在组件中调用plugin方法,我得到的结果是未定义的
<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.options=this.getSubscriberType()
}
}
我发现这个.getSubscriberType()
是未定义的
<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>
编辑:我实际上看到函数被触发(我在其中放了一个警报…但是如果我在组件中执行
console.log(this.getSubscriberType())
,我会得到未定义的…看起来您的方法实际上从未返回任何东西。$http.get()
返回一个承诺,而承诺本质上是异步的
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
}
}
})
}
}
因为函数在解析承诺之前解析,所以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值。当您
console.log(this.getSubscriberType)
不带括号时会发生什么情况我得到类似函数[{native code}]感谢它以这种方式工作,即使结果没有我想象的那么好,因为制作插件而不是直接调用组件到axios没有多少时间