1、路由(router):实现页面切换
路由 | |
<router-link> |
实现页面跳转 |
<router-view/> |
显示网页内容位置 |
2、router.js
:设置组件URL
- 组件跳转路径:
<router-link to="/">首页</router-link>
path: '/',
component: HomeView
../views/HomeView.vue
3、localStorage
:本地存储(浏览器)
<template> <div> <form @submit.prevent="doLogin"> <input type="text" v-model="username" /> <button>提交</button> </form> </div> </template> <script> export default { data() { return { username: "", }; }, methods: { doLogin() { console.log(this.username); // 本地存储(浏览器) localStorage.setItem("username", this.username); // 页面跳转 this.$router.push("/"); }, }, }; </script>
4、获取本地存储(浏览器):localStorage.getItem("username")
<template> <div id="app"> <nav> <!-- 相当于a标签:href --> <router-link to="/">首页</router-link> | <router-link to="/blog">博客</router-link>| <router-link to="/picture">图片</router-link>| <router-link to="/login">登陆</router-link> <div v-if="username"> <span>欢迎:{{ username }}</span> <button @click="logout">退出</button> </div> </nav> <router-view /> </div> </template> <script> export default { watch: { // 监听路由切换:刷新用户名 "$route.path": function () { this.username = localStorage.getItem("username"); }, }, data() { return { // 获取存储 username: localStorage.getItem("username"), }; }, methods: { logout() { // 清除本地存储(浏览器) localStorage.clear(); // 跳转页面 this.$router.push("/login"); }, }, }; </script> <style></style>
5、导航守卫forEach
(先登陆)
// 导航守卫: router.beforeEach((to, from, next) => { if (to.path !== "/login") { if (localStorage.getItem("username")) { next(); } else { next("/login"); } } next(); })