Reputation: 715
I'm trying to refactor a few components using composition api. There's a function that needs to send a request.
Since there's no access to this
on setup(props, context)
I thought I can use this context
argument like it was when I was emitting an event to parent (context.emit()
) but it seams to not be the case.
There's an error when using context:
Error in v-on handler: "TypeError: context.http is undefined""
There's an error when using this:
Error in v-on handler: "TypeError: _this is undefined"
Here's a snippet of something I'm trying to achieve:
context.http.post('/url'), { data })
.then(({ data }) => {
console.log(data)
});
Upvotes: 1
Views: 1344
Reputation: 1224
You can use vue-resource
as below, context.parent
is this
keyword. Here is the codesandbox link
main.js
import Vue from "vue";
import App from "./App.vue";
import VueCompositionApi from "@vue/composition-api";
import VueResource from "vue-resource";
Vue.use(VueCompositionApi);
Vue.use(VueResource);
Vue.config.productionTip = false;
new Vue({
render: h => h(App)
}).$mount("#app");
YourComponent.vue
<template>
<div id="app"></div>
</template>
<script>
import { onMounted } from "@vue/composition-api";
export default {
setup(props, context) {
onMounted(async () => {
await context.parent.$http
.get("https://jsonplaceholder.typicode.com/todos/")
.then(response => console.log(response.data));
});
}
};
</script>
Upvotes: 3