Search code examples
javascriptvue.jsvue-routervuejs3vue-router4

vue3 router.push doesn't update the component when url match the same route?


In a child component I meet some problem.

router config path "/blog/:user/:article"

file "Article.vue"

defineComponent({
  setup() {
    console.log("Call setup()"); // Debug info

    const route  = useRoute();
    const router = useRouter();
    const store  = useStore(); // vuex
    
    // here omits many details.
    // some axios requests depend on the variables above.

    // problem come here
    // this is a function bind to a table(or list) display in <template>.
    // but the route must change and I need to update this component based on the row.
    const rowClick = (row) => {
      router.push("/blog/" + user + "/" + row.Name);
    }
    return { rowClick };
  }
})

But that don't work, because the router think it is the same component, and refuse to reload the component.

So I don't see the Debug info in the debug cosole.

What I have try.

First I simply use the location.replace to force the application to reload the whole page.

But that doesn' elegant, it need more time to reload and history gone.

Then I try to watch the route.params but my sonsole log an vue warn which tell me that watch source must be a ref reactive obj and router push still don't update the component.

watch(route.params, (previous, current) => {
  console.log(`${previous} and ${current}`); // Debug info
})

I was confused! What should watch in the setup of vue3?

more infomation
const routes: Array<RouteRecordRaw> = [
 {
  path: "/home",
  alias: "/",
  name: "Home",
  component: Home
 },
 {
  path: "/blog/:user/:article?",
  name: "Article",
  component: () => import(/* webpackChunkName: "article" */ "@/views/Article.vue"),
 },
];

export default createRouter({
 history: createWebHistory(),
 routes: routes,
});

Note: This is my first vue project~


Solution

  • Try out to watch the route params like :

    watch(
      () => route.params, 
      ( previous, current ) => {
        console.log(`${previous} and ${current}`); 
      },
      {
        deep:true
      }
    );
    

    Note : use () => route.params instead route.params and add deep option