Home > Enterprise >  How to use router properly in VueJS
How to use router properly in VueJS

Time:08-03

I want to make my website multilingual, however when I write the code it is:

 <a  href="recruit/en">

it will give a path as: http://localhost:8080/recruit/recruit/en what if the code is:

<a  href="/en">

It takes me back to the home page again.... So what do I need to deal with here? Do I need further processing in the router.js file? Hope to get help ^^

Update: So if I handle the router like this:

    path: '/recruit',
    name: 'Recruit',
    component: () => import(/* webpackChunkName: "Recruit" */ '../views/Recruit/index.vue'),
    children: [
      {
          path: "/recruit/:locale",
          component: () => import(/* webpackChunkName: "Recruit" */ '../views/Recruit/index.vue'),
      },
  ],
  },

was it correct? and in a href tag how do i put it?

CodePudding user response:

IMHO, there is no need for nested routing here:

{
    path: '/recruit/:locale',
    name: 'Recruit',
    component: () => import('../views/Recruit/index.vue') // chunk name is set automatically.
},

Now in the template

 <a  href="/recruit/en">English</a>
                                       ^

Don't miss the leading slash. If there is no leading slash, the router just joins the path to the current URL in the browser.

CodePudding user response:

In this case you can use nested routes here.

Since your link is like this,

/recruit/recruit/en

In your routes.js file you can add,

    {
        path: "/recruit",
        component: YourComponentHere,
        children: [
            {
                path: "/recruit/:lang",
                component: YourComponentHere,
            },
        ],
    },

And you can access :lang in your child component by using,

<template>
 <h1>Language is {{ $route.params.lang }} </h1>
</template>

Or if you are using <script setup>,

<script setup>
import {useRoute} from 'vue-router';

const Router = useRoute();
</script>

<template>
 <h1>Language is {{ Router.params.lang }} </h1>
</template>

Hope this will help.

  • Related