Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

vue.js - Unable to dispatch an action after updating the route using router.push

When trying to dispatch an action after updating the route using this.$router, the action uses the previous route parameters instead of using the current route parameters.

Suppose I want to move to the /home and currently, I am on /about and in the store action called I want to access the route name, but after pushing the new route and then calling the action, it is using the previous route only and not the updated one.

this.$router.push('/home', this.$store.dispatch('called'))

Also, I tried using this.$router.push('/home').then(this.$store.dispatch('called')), but it gives undefined error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could pass the old and new queries from the method:

methods: {
  changeRoute() {
    const queryNew = { id: 1 };                              // Create new query
    const queryOld = { ...this.$route.query };               // Clone old query
    this.$router.push({ path: '/home', query: queryNew });   // Navigate
    this.$store.dispatch('called', { queryNew, queryOld });  // Call the action
  }
}

The action signature should look like:

actions: {
  called({ commit }, { queryNew, queryOld }) {
    console.log(queryNew, queryOld);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...