0
votes

I'm super new to nuxt and have picked up a large project. I can't work out how other views are doing it, but I want to run an axios on page load, could someone help me?

The way this project is structured is it has a store folder (guessing this is vuex), and get a getter.js, mutations.js, index.js, state,js, and actions.js (apologies if this is the natural way) not sure if the way my project does it is a custom design pattern or if its just the goto way with nuxt / vuex

So far I have tried this,

computed: {
  plans: 'accountBilling/fetch',
},

But I believe this is for the getters.js file?

I have an actions.js file, and want to call and receive the response from fetch on page load?

export default {
  async fetch({ commit }, { account_id }) {
    return await this.$axios.get(`/accounts/billing/plans`)
      .then(response => { commit('setPlans', response.data); response.data })
      .catch(error => { throw error })
  },
}
2
Can you share folder structure of store folder and code of state.js?Andrew Vasilchuk

2 Answers

0
votes

In your root component, in the mounted hook:

mounted() {
  this.$store.dispatch("fetch");
}

And then to get plans:

computed: {
  plans() { return this.$store.state.plans; }
}
0
votes

In Nuxt.js you don't really have a root component as such. You could use the index.vue component but if someone enters your web app via a different page the function won't be called. So I found the best way is to use the middleware function that is baked into Nuxt.

First, create a middleware folder in your root (if you don't have one already) and add a file onload.js.

Add the below code in the file:

export default function ({store}) {
    store.dispatch('fetchMenu')
    // Or whatever action you want to call
  }

Then add this middleware to your nuxt.config.js

...
 router: {
    middleware: ['onload']
  },
...