问题
So, this my Api Service Component, I'm using Axios:
import api from './Api.vue';
export default {
name: 'app-feed-service',
methods: {
getPosts() {
return api.get('posts/');
}
}
}
and some feed component
import AppSinglePost from './../Feed/Post.vue';
import AppFeedService from './../../api/Feed.vue';
export default {
name: 'app-posts',
components: {
AppSinglePost
},
data() {
return {
posts: []
}
},
created() {
AppFeedService.getPosts().then((res) => {
console.log(res);
});
}
}
and now the error:
TypeError: __WEBPACK_IMPORTED_MODULE_1__api_Feed_vue___default.a.getPosts is not a function
can anybody help?
回答1:
It looks like AppFeedService as defined in Feed.vue is not really a component, it's just a collection of services you want to call. Since you have defined it as a component, the component would have to be instantiated somewhere, which in most cases would mean you used it in another component's template
.
You can just define it as an object instead.
import api from './Api.js';
export default {
getPosts() {
return api.get('posts/');
}
}
Same thing for your Api.vue file likely. You only need to use a .vue
file when you are defining an actual component.
Then in your feed component just
import AppFeedService from './../../api/Feed.js';
To summarize: the .vue
file format is meant for defining single file components. You only need a .vue
file when you are actually defining a single file component (something that would probably be used in the template
of a different component). If you just want an object that contains a collection of methods or some state, just define it with plain javascript.
回答2:
I was getting the exact same error as Webpack compile error: TypeError: WEBPACK_IMPORTED_MODULE_1 … is not a function in ReactJS. This type of error you get usually when you are importing any defined variable/ component from any other file as Component. In react we import component as
import ComponentName from '/componentPath';
so if it isn't a component we are importing then try using importing as an Object
import { componentName } from '/componentPath';
The { } are the nameplates for an Object.
来源:https://stackoverflow.com/questions/43946738/webpack-compile-error-typeerror-webpack-imported-module-1-is-not-a-funct