首先,提前感谢您的反馈。
由于我对es6和vuejs还不熟悉,所以在整个应用程序中使用导入的服务模块开始出现问题。最终目标是把使用AXIOS的所有东西也移到一个基础服务上。
[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");
}
}
应用程序.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);
});
}
}
最佳答案
如果要使用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");
}
}