【问题标题】:Vue Axios Mixin global method type undefinedVue Axios Mixin 全局方法类型未定义
【发布时间】:2020-01-02 13:48:33
【问题描述】:

我正在努力使用一个全局的 Vue mixin 方法,我希望能够在每个组件中使用它,这样我就不必在所有这些组件中重复相同的方法。

AxiosMixin.js:

import axios from 'axios';
export default {
    methods: {
        getAllUsers (){
            axios.get('/user/')
            .then(response => {
                return response.data.resources
            })
            .catch(errors => {
                window.console.log(errors)
                return
              })
        }
    }
}

Main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import crytojs from 'crypto-js'
import vuetify from './plugins/vuetify'
import 'material-design-icons-iconfont/dist/material-design-icons.css';
import mixin from './AxiosMixin'

Vue.config.productionTip = false
Vue.mixin({
  methods: {
    getAllUsers: mixin.getAllUsers
  }
})

new Vue({
  router,
  store,
  axios,
  vuetify,
  crytojs,
  render: h => h(App)
}).$mount('#app')

在组件中:

  created () {        
        const users = this.getAllUsers();
        users.forEach((user) => {
            this.allUsers.push({
                userid: user.u_id, 
                userinfo: user.u_first_name+" "+user.u_last_name+" ("+user.u_telephone+")",
            });
        });
    }

但这不起作用。我收到错误消息:方法“getAllUsers”在组件定义中具有“未定义”类型。您是否正确引用了该函数?

我尝试将 main.js 中的代码更改为: getAllUsers: () => mixin.getAllUsers() ,但这会导致错误:TypeError: _AxiosMixin__WEBPACK_IMPORTED_MODULE_12__.default.getAllUsers is not a function

我已经搜索了所有较旧的问题,但无法解决我的问题。我还阅读了文档:https://vuejs.org/v2/guide/mixins.html

任何帮助将不胜感激!

【问题讨论】:

    标签: vue.js methods axios global mixins


    【解决方案1】:

    问题出在

    Vue.mixin({
      methods: {
        getAllUsers: mixin.getAllUsers
      }
    })
    

    getAllUsers: mixin.getAllUsers改成getAllUsers: mixin.methods.getAllUsers

    但是您的 AxiosMixin.js 已经包含 Vue 期望格式的 mixin 对象,因此您可以将上述所有代码替换为 Vue.mixin(mixin)


    还有另一个问题 - 您的 getAllUsers 没有返回任何内容。 将axios.get('/user/')... 更改为return axios.get('/user/')...,这样你的函数就会返回一个promis(用户)

    然后像这样使用它:

    created () {        
       this.getAllUsers().then(users => ...do something with users...)
    }
    

    【讨论】:

    • 感谢您的回复。我更改了我的代码,但知道我收到以下错误: 创建钩子中的错误:“TypeError:无法读取未定义的属性 'forEach'” 我会假设我的组件不理解“this.getAllUsers()”是什么?
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 2019-01-01
    • 2020-05-04
    • 2019-01-05
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2019-03-08
    相关资源
    最近更新 更多