首先要提前感谢您的反馈。 因为我是es6和vuejs的新手,所以在整个应用程序中使用导入的服务模块时我开始遇到问题。最终目标是将使用Axios的所有内容移动到一个BaseService。
[Vue warn]: Error in mounted hook: "TypeError: __WEBPACK_IMPORTED_MODULE_0__services_AuthService__.a.getCurrentUser is not a function"
AuthService.js
import BaseService from './BaseService'
export default class AuthService {
setCurretUser( user )
{
localStorage.setItem("currentUser", user);
}
getCurrentUser()
{
return localStorage.getItem("currenUser");
}
}
App.vue
import Axios from 'axios'
import Navbar from './partials/Navbar'
import Sidebar from './partials/Sidebar'
import AuthService from '../services/AuthService'
export default {
name: 'app',
components: {
Navbar,
Sidebar
},
mounted() {
console.log('Component mounted.')
},
created() {
Axios.get('api/user')
.then(function (response) {
AuthService.setCurrentUser(response.data);
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}
答案 0 :(得分:3)
如果要将AuthService
类用作方法的容器,请将它们转换为static
,以便可以在不实例化类(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Static_methods)的情况下调用它们
export default class AuthService {
static setCurretUser( user )
{
localStorage.setItem("currentUser", user);
}
static getCurrentUser()
{
return localStorage.getItem("currenUser");
}
}
或者您也可以在对象中包含它们:
export default {
setCurretUser( user )
{
localStorage.setItem("currentUser", user);
},
getCurrentUser()
{
return localStorage.getItem("currenUser");
}
}