vue3路由简单配置

文档,从vue2.x迁移

https://router.vuejs.org/zh/guide/migration/index.html

路由目录

各文件内容

【router/index】

import { createRouter, createWebHashHistory, createWebHistory} from "vue-router";
import { scrollBehavior } from "./helpers/scroll";
import routes from "./routes"

/**
 * 路由模式,hash、history
 * base 配置被作为 createWebHistory (其他 history 也一样)的第一个参数传递
 */
const history = process.env.VUE_APP_ROUTER_MODE === "hash" ? createWebHashHistory(process.env.BASE_URL) : createWebHistory(process.env.BASE_URL)

const router = createRouter({
    history,  
    routes,
    scrollBehavior,
})

// 动态改变页面标题
router.beforeEach((to, from, next) => {
    if (to.meta.title) {
      document.title = to.meta.title;
    }
    next();
});

const setupRouter = (app) => {
    app.use(router);
};

export {
    setupRouter,
};

【main.js】

import { createApp } from "vue";
import App from "./App.vue";
import { setupRouter } from "@/router/index";

const app = createApp(App); //创建vue实例

async function setupApp() {
    /* 路由 */
    setupRouter(app)
    app.mount("#app");
}

setupApp();

【router/helper/scroll.js】

export const scrollBehavior = (to, from, scrollPosition) =>{
    if (scrollPosition && to.meta.keepAlive) {
        //返回缓存页面后记录浏览位置
        return scrollPosition;
    }
    return { left: 0, top: 0 };
}


【router/routes/other.js】

const routes = [
    {
        path: "/other",
        component: ()=>import("@/layouts/basic-view"),
        redirect: "/other/about-us",
        children: [
            {
                path: "/other/about-us/:id",
                name: "about-us",
                component: ()=>import("@/views/other/about-us"),
                meta: {
                    title: "关于我们",
                },
            },
            {
                path: "/other/contact-us",
                name: "contact-us",
                component: ()=>import("@/views/other/contact-us"),
                meta: {
                    title: "联系我们",
                },
            },
        ]
    }
];

export default routes;

【router/routes/index.js】



//引入各模块路由分支
import AccountRoute from "./account"; //账户
import OtherRoute from "./other"; //其他

const routes = [
    {
        path: "/",
        component: ()=>import("@/layouts/basic-view"),
        children: [
            {
                path: "/",
                name: "home",
                component: ()=>import("@/views/home/home"),
                meta: {
                    title: "首页",
                },
            },
        ],
    },
    ...AccountRoute,
    ...OtherRoute,
    {
        path: "/:pathMatch(.*)*",
        name: "not-found",
        component: ()=>import("@/views/home/not-found"),
        meta: {
            title: "页面不存在",
        },
    },
];

export default routes;

路由跳转

【FROM】

<template>
    <div class="container">
        <button class="mr-20" @click="goHome">首页</button>
        <button class="mr-20" @click="goAboutUs">关于我们</button>
        <button class="mr-20" @click="goContactUs">联系我们</button>
    </div>
</template>

<script>
import { useRouter } from "vue-router";
export default {
    setup() {
        const $router=useRouter()
        function goHome() {
            $router.push({ name: "home" });
        }
        function goAboutUs() {
            $router.push({ name: "about-us", params: {id: 666} });
        }
        function goContactUs() {
            $router.push({ name: "contact-us" });
        }

        return {
            goHome,
            goAboutUs,
            goContactUs,
        };
    },
};
</script>

<style scoped lang="less"></style>

【TO】

<template>
    <div class="container">
        about-us
        {{ $route.params.id }}
    </div>
</template>

<script>
import { useRoute } from "vue-router";
import {onActivated} from "vue"
export default {
    name: "",
    // beforeRouteEnter(to, from, next) {
    //     console.log(to);  
    //     console.log(from);
    //     next()
    // },
    setup() {
        const route = useRoute();
        console.log(route.params.id);
        onActivated(()=>{
            console.log("此页面被缓存了")
        })
    },
};
</script>

<style scoped lang="less"></style>


keepAlive配置


<template>
    <router-view v-slot="{ Component }">
        <component :is="Component" v-if="!$route.meta.keepAlive" />
        <keep-alive>
            <component :is="Component" v-if="$route.meta.keepAlive" />
        </keep-alive>
    </router-view>
</template>



meta: {
    title: "关于我们",
    keepAlive: true
},

keepAlive配置【补充说明:关于二级及以上路由的缓存】

注意:此方法后期验证行不通,解决方案为只设置一个Layout,不要设置basic-view,blank-view等多个layout

若页面有二级及以上路由,那么不仅需要在App.vue里做keepAlive配置,还需要子路由里做同样的keepAlive配置。
如在最外层layout里配置,如图

无卡顿刷新页面--reload配置


<script>
import { ref, provide, nextTick } from "vue";

export default {
    name: "App",
    setup() {
        const isRouterAlive = ref(true);
        provide("reload", () => {
            isRouterAlive.value = false;
            nextTick(() => {
                isRouterAlive.value = true;
            });
        });
        return { isRouterAlive };
    },
};
</script>

当前页面提示用户登录,用户登录成功后再跳转回当前页面

import { useRouter, useRoute } from "vue-router";
const $route = useRoute();
const $router=useRouter();


【当前页跳转至登录页方式】
$router.replace({
    path:"/user/login",
    query: {redirect: $router.currentRoute.value.fullPath.split("redirect=").pop()}
})

【登录成功后返回】
if($route.query.redirect){
    $router.replace({path:decodeURIComponent($route.query.redirect)})
}else{
    $router.push('/')
}
posted @ 2022-09-23 17:09  huihuihero  阅读(1185)  评论(0编辑  收藏  举报