E
E
Evgeny Zhurov2019-11-21 20:14:55
Vue.js
Evgeny Zhurov, 2019-11-21 20:14:55

Why is vue-router not changing the data in the component?

Hello. The application has a header with navigation, let's say this kind:

<nav>
<router-link
        tag="a"
        :to="{ name: item.name, params: { slug: item.slug }}"
      >
        {{ item.text }}
      </router-link>
</nav>

items on which v-for is traversed looks like this:
[
{
            name: 'InnerTable',
            slug: 'data-1',
            text: 'Link 1',
          },
{
            name: 'InnerTable',
            slug: 'data-2',
            text: 'Link 2',
          }
]

route for the items in this menu looks like this:
{
    path: '/:slug',
    name: 'InnerTable',
    component: AppInnerTable,
    props: true
  }

That is, you need to use the same component to display different data, depending on the routing. For example, two elements in the array, respectively - two links in the menu, each of which should lead to the same component, but fill it with different data, i.e. when clicking on the link, re-download json with data and re-render the component
In the component that the routing points to, I receive data via axios:
created: function() {
    let data_slug = this.$route.params.slug

    Axios.get(`/data/${data_slug}.json`)
      .then(res => {
        this.table_data = res.data
      })
      .catch(error => {
        console.log(error)
      })
  }

And then this data is mounted to the application.
So this whole story works like one time. If I follow the link from the main page, then everything is fine. But if, being on this "internal" page, I click on another link, then the url in the address bar changes, but nothing else happens. There are no errors in the console. At the same time, if you reload the page with the updated url, then the correct data is rendered. What am I doing wrong and how to fix it?
More visually
Please do not just throw links to the documentation. Or throw, but with an explanation, because. I did not see the solution in the documentation, or, perhaps, I simply did not understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-11-21
@Zhuroff

Because the component instance is not re-created when changing parameter values. They need to be followed:

watch: {
  '$route.params.slug': {
    immediate: true,
    handler() {
      // сюда переносите код из created
    },
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question