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>
<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();
})