0👍
✅
thanks to connexo and estus flask in the comments. i’ve come to know that there is something called vuex that will do the work for you.
here is the syntax.
main.js:
import { createApp } from "vue";
import { createStore } from "vuex";
import showPage from "./components/showPage.vue";
// Store
const store = createStore({
state() {
return {
getjson: null,
};
},
mutations: {
getfile(state) {
axios
.get("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => {
if (state.getjson == null) {
state.getjson = response.data;
}
});
},
},
});
// App
const app = createApp(showPage);
app.use(store);
app.mount("#app");
In the component:
<template>
<!-- run setposts before using getjson -->
{{this.setposts()}}
{{this.$store.state.getjson}}
</template>
<script>
export default {
methods:{
setposts(){
this.$store.commit("getfile");
}
}
};
</script>
Source:stackexchange.com