vue3使用vue-router路由插件
vue-router
使用
1.命令行安装(vue3要用版本四)
npm i vue-router@4
2.配置路由文件, 位与src/router/index.js
// 1.第一个参数用来创建路由
// history模式 --- 引入的第二个函数是设置history路由模式
// 若为createWebHashHistory, 则是
import {
createRouter, createWebHistory } from "vue-router";
import AnswerList from "../components/AnswerList.vue";
import ProblemList from "../components/ProblemList.vue";
import ShareList from "../components/ShareList.vue";
import SolveProblem from "../components/SolveProblem.vue";
import UserMsg from "../components/UserMsg.vue";
// 2.配置组件路由
const routes = [
// 路由的默认路径
{
path: "/",
redirect: "/shareList",
},
// name路由名称,path组件路由的路径,component对应组件
{
name: "answerList", path: "/answerList", component: AnswerList },
{
name: "problemList", path: "/problemList", component: ProblemList },
{
name: "shareList", path: "/shareList", component: ShareList },
{
name: "solveProblem", path: "/solveProblem", component: SolveProblem },
{
name: "userMsg", path: "/userMsg", component: UserMsg },
];
// 创建路由对象
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
3.在 main.js
中引入并使用路由
// 引入路由
import router from "./router";
const app = createApp(App);
// 使用
app.use(router);
app.mount("#app");
4.组件中使用
显示区:
keep-alive
整个页面缓存
<!--写法一: -->
<router-view></router-view>
<!--写法二: 所有页面都缓存-->
<keep-alive>
<router-view></router-view>
</keep-alive>
<!--写法三: 指定所有页面都缓存-->
<!-- <keep-alive>-->
<!-- <router-view></router-view>-->
<!-- </keep-alive>-->
跳转区:
①链接式
这里的to用的是路由中的path
<router-link to="/home">home</router-link>
<router-link to="/about">about</router-link>
②函数式
在js中
import {
useRouter } from "vue-router";
setup(){
// 使用路由
const router = useRouter();
// 使用路由名称跳渲染指定页面
router.push({
name: "answerList" });
}