3

I have a component

<template>somecode</template>
<script>
 export default {
        name: 'Card',
        created() {
                axios.get(apiObjUrl)
                      somecode
                })
     }
</script>

this my url: http://127.0.0.1:8080/#/card/12

But I have a problem:

when I use router-link like this:

<router-link to="/card/155"> card 155</router-link>

my url changes: http://127.0.0.1:8080/#/card/155

but the created() method doesn't get fired. so I don't make new xhr request to api and data not changes what do I do?

1

2 Answers 2

6

As an alternative you can setup a key attribute on your <router-view> like this:

    <router-view :key="$route.fullPath"></router-view>

As <router-view> is a component itself and unique keys force replacement of component instead of reusing it. So you can make use of life cycle hooks.

See the fiddle

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

2 Comments

whta exactly :key attr does here?
@user2950593key tells Vue’s virtual DOM algorithm to identify VNodes when diffing the new list of nodes against the old list. In simple words it tells vue that the node should be replaced (rerendered) with a new one as new key is passed with a new route path on every route change.
4

That's just because your component is already created. You may try using the lifecycle hook updated() instead of created().

 export default {
   name: 'Card',
   updated() {
     axios.get(apiObjUrl)
     somecode
   })
 }

Note: This will only work if your DOM changes. If you just want to listen on url changes and update accordingly you better $watch your route like this.

export default {
  name: 'Card',
  created() {
    axios.get(apiObjUrl)
    somecode
  }),
    watch: {
    '$route': function() {
        // do your stuff here
    }
    }
}

4 Comments

when I change created method to updated updated method doesn't get fired the first time I load the page(I don't know why) nothing in console
I don't really got it
I need to call the same code axios.get(apiObjUrl) on page created when I refresh the page, and on url change with router-link, so how do I exactly do it?
I've edited my code, there was a little mistake. Leave your current code as it is and add the watch property to it. This can take in any property you want and listen on changes. Whenever a change happens (in this case whenever your url changes) it'll just fire up any expressions within its execution block. More here: vuejs.org/v2/api/#vm-watch

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.