user2950593
user2950593

Reputation: 9627

vue js component doesn't rerender on the same page

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?

Upvotes: 3

Views: 1947

Answers (2)

Vamsi Krishna
Vamsi Krishna

Reputation: 31352

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

Upvotes: 6

Aer0
Aer0

Reputation: 3907

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
    }
    }
}

Upvotes: 4

Related Questions