vue create xxx
不要选默认的那个,选人工,然后下面选上router,然后一路回车
<router-link to="/">Home</router-link> 相当于<a>
这些路径存在router文件夹下的index.js中
点击/about就会跳到component组件 => views下的About组件
点击rout-link标签会用to属性跳转到相应url,然后找到这个url对应的组件,从views下显示出来
小组件放在components中,整体页面组件放在views中
博客登录页
App.use
<template>
<div id="app">
<div id="nav">
<router-link to="/">首页</router-link>|
<router-link to="/blog">博客</router-link>|
<router-link to="/video">视频</router-link>||
<span v-if="show">
welcome: {{ this.username }} <button @click="logut">注销</button>
</span>
</div>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
username: localStorage.getItem("usr"),
show: localStorage.getItem("usr"),
};
},
//但是此时登陆后跳转到首页后需刷新才能显示出来
//可以用监听器监听路由变换,一旦变化,使username = localstorage.get
watch: {
"$route.path": function () {
this.username = localStorage.getItem("usr");
},
},
methods: {
logut() {
//清空本地存储
localStorage.clear();
this.$router.push("/login");
},
},
};
</script>
login.vue
<template>
<div>
<form @submit.prevent="doLogin()">
<input type="text" v-model="username" />
<input type="text" />
<button value="submit">登录</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
username: "",
};
},
methods: {
doLogin() {
//将用户名直接提交保存起来
//本地存储
//localStorage,将usr内容指定为username,然后可以在其他页面拿到usr
console.log(this.username);
localStorage.setItem("usr", this.username);
console.log(localStorage.getItem("usr"));
//vue的路由提供编程式导航
this.$router.push("/");
},
},
};
</script>
index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Blog from '../views/Blog.vue'
import Video from '../views/Video.vue'
import Login from '../views/Login.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/blog',
name: 'Blog',
component: Blog
},
{
path: '/video',
name: 'Video',
component: Video
},
{
path: '/login',
name: 'Login',
component: Login
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
//导航守卫
router.beforeEach((to, from, next) => {
if (to.path !== "/login") {
if (localStorage.getItem("usr")) {
next()
} else {
next("/login")
}
} else {
next()
}
})
export default router