3

So I have a component which executes code once it's mounted like this:

mounted(){
  axios.get('/markers/' + this.username)
    .then(response => {
      this.markers = response.data.markers
    }).catch((error) => console.log(error));
}

And I get the username like this:

username: this.$route.params.username

however, if I change the URL parameter, the username doesn't update so my AXIOS call doesn't update my markers. Why is this happening?

7
  • You might need to use Dynamic Route Matching, see if this post helps. Commented Jan 18, 2019 at 9:46
  • 4
    Did you set the key prop on the <router-view /> component? i.E. <router-view :key="$route.fullPath" />? This might be needed for the mounted hook to trigger when switching between view components. Commented Jan 18, 2019 at 9:48
  • What do you mean by "The username doesn't update". I don't see any code here that updates the username property, could you include the whole file? What does your data() function look like, why not just call /markers/' + this.$route.params.username Is there any errors happening? This needs more information please. Commented Jan 18, 2019 at 9:48
  • @swonder, he meant that if you go to route /markers/john, and then you navigate to /markers/smith, it will still show john Commented Jan 18, 2019 at 9:51
  • Well since the username is set based the username param in the URL, I assumed it would update automatically if I change the url, however, it doesn't. Nothing else in my code is relevant to my issue. Exactly what ljubadr said. Commented Jan 18, 2019 at 9:52

1 Answer 1

13

The reason is simple, even thought the URL is changing the component is not, VueJS is basically reusing the component and therefore not calling the mounted() method again.

Usually you can just setup a watcher and refactor a bit your code

methods: {
    fetchData(userName) {
        axios.get('/markers/' + this.username)
        .then(response => {
            this.markers = response.data.markers
        }).catch((error) => console.log(error));
    }
},
watch: {
    '$route.params': {
        handler(newValue) {
            const { userName } = newValue
   
            this.fetchData(userName)
        },
        immediate: true,
    }
}

EDIT: Added the immediate true option and removed the mounted() hook

Sign up to request clarification or add additional context in comments.

3 Comments

Pretty much what I said in my comment, I didn't think the component would "mount" again if you're changing to the exact same component. This confirms that. Nice work.
I'm curious, will the watch handler() fire if user goes to completely different route?
Not if the new route renders another component

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.