安装
参考文档: https://github.com/vuejs/vue-router-nextnpm install vue-router@4
配置
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{ path: "/", name: "home", component: Home },
{ path: "/login", name: "login", component: Login },
{ path: "/columnDetail/:id", name: "columnDetail", component: ColumnDetail },
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
在main.js中安装
createApp(App).use(Router).mount("#app");
使用
使用router-link跳转
# 1.基础跳转
<router-link class="btn btn-outline-light my-2" to="/columnDetail">
注册
</router-link>
# 2.1 使用param传参
<router-link
class="btn btn-outline-light my-2"
:to="{ name: 'column', params: { id: 123 } }"
>
注册
</router-link>
# 2.2 使用query传参
<router-link
class="btn btn-outline-light my-2"
:to="{ name: 'column', query: { id: 123 } }"
>
注册
</router-link>
# 3.使用模板字符串传参
<router-link
class="btn btn-outline-light my-2"
:to="`/columnDetail/${456}`"
>
注册
</router-link>
查看当前路由详细参数
import { useRoute } from "vue-router";
const route = useRoute();
console.log("route", route);
使用router进行跳转
import { useRouter } from "vue-router";
// 普通跳转
const toColumnDetail = () => {
router.push("/columnDetail/121212");
};
// 传参
const toColumnDetail = () => {
router.push({
name: "columnDetail",
params: { id: "222222" },
});
};