简体   繁体   中英

How to set watcher for router-view i vue

I'm begginer in vue and i can't resolve my problem with VueRouter.

I got main app component like

<template>
 <div>
  <Header />
  <router-view />
  <Footer />
 </div>
</template>

One of my Router components has an function to get data from database.

import axios from 'axios';

export default {
    name: 'ComponentName',
  data() {
    return {
      dataFromDatabase: []
    }
  },
  methods: {
    getData: function() {
      // Axios get function  to get data from database and add it to this.dataFromDatabase array
    }
  },
  created() {
    this.getData();
  }
}

Given data are based on url params and it should be changeable when clicking on link that are in header or in other places in a whole app. The problem is that it cannot change if the component won't reload. I know that the problem is that function is called after component is created and is not called again.

So my question is: Is there any way to watch for url params changes (adding this.$route.params.param to watch() function is not working). Maybe there is a better way to set up my routes or other way to call a function except of created() function or maybe component would reload everytime the link change. As i said links to this can be everywhere even in components that are not setted up in Router

You probably just need watch which by the way is not a function but an object with methods inside

watch: {
  '$route'() {
    // do something
  }
}

you can use a smart watcher that will be watching since the component was created:

watch: {
  '$route': {
    immediate: true,
    handler(newValue, oldValue) {
      // ...
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM