I’m learning Vue with Vuex, I made a method called ‘llamarJson’this method get a json data. I don’t know how to use it when the page load. I tried many ways but I could not find a solution. I’m using Vue and Vuex. Please, could you help me?
That’s the code html:
<!DOCTYPE html> <html> <head> <title>Vue</title> <!-- Vue --> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <!-- Vuex --> <script src="https://unpkg.com/vuex@3.6.0/dist/vuex.js"></script> </head> <body> <div id="caja-vue"> <actividades></actividades> </div> <script src="codigo.js"></script> </body> </html>
That’s the JS code:
//componentes Vue.component('actividades', { template: /*html*/ ` <div> <h1>Hello friend</h1> <ul v-for="item of actividades"> <li>{{ item.name }}</li> </ul> </div> `, computed: { ...Vuex.mapState(['actividades']) }, methods: { ...Vuex.mapActions(['llamarJson']) } }); //VueEx const store = new Vuex.Store({ state: { actividades: [], programas: [] }, mutations: { llamarJsonMutation(state, llamarJsonAction){ state.actividades = llamarJsonAction; } }, actions: { llamarJson: async function(){ const data = await fetch('https://jsonplaceholder.typicode.com/users'); const actividades = await data.json(); commit('llamarJsonMutation', actividades); } } }); //Vue new Vue({ el: '#caja-vue', store: store });
Advertisement
Answer
you should use vue life cycle hooks for this, read the link below:
these are vue hooks:
Creation Hooks
beforeCreate(): events and lifecycle have been initialized but data has not been made reactive
created(): you have access to data and events that are reactive but templates and virtual DOM have not yet been mounted or rendered
Mounting Hooks
beforeMount(): runs before the initial render
mounted(): you have access to the reactive component, templates and rendered DOM
Updating Hooks
beforeUpdate(): runs after data changes and before the DOM is re-rendered
updated(): runs after data changes and the DOM is re-rendered
Destruction Hooks
beforeDestroy(): runs before tear down
destroyed(): runs after tear down
for page load depending on your need (if you want to have access to DOM or not) you may use created()
or mounted()
hooks.
just define them in your vue component object and call your method in them like this:
created() { this.someMethod(); }
in your case you can also call the vuex action from the created (or any other hook) directly like this:
created() { this.$store.dispatch('vuexAction'); }