Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - Vue.js - update router view

I am new to Vue.js and encountered this problem.

I have this simple piece of code in App.vue

<div v-for="brand in response" v-bind:key="brand.BrandId">
    <router-link v-bind:to="{name: 'brand', params: {brandId: brand.BrandId } }">
        {{brand.Name}}
    </router-link>
</div>
<router-view />

The router/index.js routes array item looks like this:

{
    path: '/brand/:brandId',
    name: 'brand',
    component: () => import('../views/BrandDetail.vue')
}

I received the response from API. It is a valid array of objects. The menu is showing fine.

I would expect the router view to update on the click of the router-link. It does update the URL (#/brand/id), but the router view does not update.

There are other router-links that are hardcoded. If I go there and back to any dynamically added router-link it works as expected but if I click one dynamic router-link and then another the router-view is stuck in the first one.

I also tried to add a reactive data source to the key but that did not help.

Can someone explain to me what is going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This happens when you enter a route you are already on, and the component is not reloaded, even though the parameters are different. Change your router-view to:

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

Vue tries to reuse components when possible, which is not what you want in this situation. The key attribute tells Vue to use a different instance of a component for each unique key rather than reusing one. Since the path is different for each set of parameters, that will make a good key.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...