问题
Trying to use vue-resource but i am etting the error described in the title. The code below is in utils section called network.js:
import VueResource from 'vue-resource'
const getConfig = () =>{
console.log('its working');
// GET /someUrl
this.$http.get('https://fdsdfsdf-685a-45ed-8665-9847e0dbce0d.mock.pstmn.io/getConfig')
.then(response => {
// get body data
this.config = response.body;
}, response => {
// error callback
});
};
//Export login so other classes can use it
export{
getConfig
}
And this the code where it gets called. It exists in one of my routes called Admin.vue:
<template>
<div class="admin">
<h1>This is admin page area</h1>
<p>This is the data: {{this.config}}</p>
</div>
</template>
<script>
import{getConfig} from "../utils/network";
export default{
data: function () {
return {
config: [{}]
}
},
created:function(){
getConfig();
}
}
</script>
I am using it as they describe in the example i am not really sure what i am missing?
回答1:
network.jsis missing a call toVue.use(VueResource), as documented for Webpack projects:import Vue from 'vue' import VueResource from 'vue-resource' Vue.use(VueResource)And
getConfig()is an arrow function, which permanently binds a lexicalthis(callers cannot rebind this), andthisisundefinedin the scope ofnetwork.js.If you intended for callers (i.e., the components) to specify itself as the context via Function.prototype.call, you'd have to declare
getConfigas a regular function:// network.js const getConfig = function() { ... } // option 1 function getConfig() { ... } // option 2 // MyComponent.vue > script import { getConfig } from '../utils/network.js' export default { created() { getConfig.call(this) } }demo
Another solution is to use mixins so that you could call
this.getConfig()(without passing the context):// network.js const getConfig = function() { ... } // option 1 function getConfig() { ... } // option 2 const getConfigMixin = { methods: { getConfig } }; export { getConfigMixin } // MyComponent.vue > script import { getConfigMixin } from '../utils/network.js' export default { mixins: [getConfigMixin], created() { this.getConfig() } }demo
来源:https://stackoverflow.com/questions/53797498/typeerror-cannot-read-property-http-of-undefined