0
votes

I am using Nuxt.js with Vuex and I would like to trigger a mutation when somebody enters in my web with a certain parameter (ex: https://example.com/?param=abc), and pass the parameter to a state.

I tried to check the documentation of the watchQuery property https://nuxtjs.org/api/pages-watchquery, but there’s no examples about how to do this, I just found this How to watch on Route changes with Nuxt and asyncData but I can’t see any way of how to write an action in Vuex store with watchQuery.

I tried writing:

actions: {
    watchQuery: true,
    asyncData ({ query, app }) {
       const { start } = query
       const queryString = start ? `?start=${start}` : ''
       return app.$axios.$get(`apps/${queryString}`)
       .then(res => {
           commit('setParam',res.data);
       })
    },
}

But that syntax is not allowed.

Any help would be welcome, thanks in advance!

1

1 Answers

3
votes

From my understanding watchQuery sets a watcher for query string, meaning it's waiting for the query to change while the page is already rendered making it possible to call methods like asyncData() again.
Since you only want to save a certain parameter when the user enters the page and then pass the paramater to a state you just need to move your asyncData method to a page from which you want to get the parameter, you will also need to extract store and query from the context automatically passed into asyncData and then using the store and query save the query parameter into your state.

Here is a simple demonstrantion

// Your page from which you want to save the param
export default {
  asyncData({store, query}) { // here we extract the store and query
    store.state.somethingForSavingTheParam = query.nameOfTheParamYouWantToSave
     // instead of using store.state you could use store.commit(...) if that's what you want
  }
}