vue3子页面创建及使用
子页面创建及使用
·
一,在router目录下的index.js中创建。
import { createRouter, createWebHashHistory } from "vue-router";
// 引入文件
import Home from "../views/Home.vue";
import About from "../views/About.vue";
import Attach from "../views/Attach.vue";
// import Sy from "../views/Sy.vue";
import Cs from "../views/Cs.vue";
const routes = [
{
path: "/Attach",
redirect: Attach,
},
{
path: "/home", //假如home为登录页面
name: "home",
component: Home,
},
{
path: "/",
name: "About", //为首页
component: About,
children: [ //子页面
{
path: "/",
name: "Attach",
component: Attach,
},
{
path: "/Cs",
name: "Cs",
component: Cs,
},
{
path: "/sy",
name: "sy",
component: sy,
}
],
},
];
const router = createRouter({
routes,
history: createWebHashHistory(),
});
常见的后台管理登录页面及页面。
主页代码在router里面path默认/是主页:
<template>
<div>
<div>
<p>侧面菜单</p>
</div>
<div>
<p>面包屑</p>
</div>
<div>
<p><router-view></router-view></p>
</div>
</div>
</template>
主页面样式:
cs页面:测试页面
<template>
<div>
<p>测试</p>
</div>
</template>
sy页面:子页面:首页
<template>
<div>
<p>首页</p>
</div>
</template>
把子页面嵌套到主页面:router-view默认把子页面的内容传过来,也就是我们的Attach页面
<template>
<div>
<div>
<p>侧面菜单</p>
</div>
<div>
<p>面包屑</p>
</div>
<div>
<p><router-view></router-view></p>
</div>
</div>
</template>
添加点击事件:我们这里就给面包屑添加了,可根据自己的需求添加。
<template>
<div>
<div>
<p>侧面菜单</p>
</div>
<div>
<p @click="isHref">面包屑</p>
</div>
<div>
<p><router-view></router-view></p>
</div>
</div>
</template>
<script setup>
// import { useStore } from "vuex";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const route = useRoute();
const isHref = (url) => {
router.push({ name: "cs" });
};
</script>
当点击时:
在点击时只有子页面发生改变,其他不变。
这样就有问题了当我们运行文件时就会发现一进去不是登录页面,那如何解决?
一、可以使用导航守卫:可见导航守卫详情
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
// const touye = new vueRourter({...})
router.beforeEach((to, from, next) => {
// to当前路由信息
let scienceid = sessionStorage.getItem("scienceid"); //这是我们登录时存到本地里面
if (to.name != "home") { //判断当前页面如果不是登录页面
if (scienceid) { //是的话判断如果本地有值的话就可以执行下个页面
next();
} else {
router.replace("home"); //没有的话强制返回登录页面
}
} else { //当是登录页面的话
if (scienceid) { //并且本地里面有值的话触发子页面
router.replace("/"); //这个‘/’页面是子页面的主页
} else { //如果本地里面没有数据可以单击跳转其他页面
next();
}
}
});
export default router;
二、可以当我们点击登录时本地存储一个数据(随意数据),当我们运行时判断如果本地没有数据强制跳转到登录页面。
这样就解决了运行进去不是登录页面的问题了。
更多推荐
已为社区贡献6条内容
所有评论(0)