1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Document</title>
7 </head>
8 <body>
9 <!-- 普通组件引用<组件名/>是包含关系。路由是跳转到 -->
10 <!-- 1.搭建页面功能结构模板 -->
11 <div id="app"></div>
12 <template id="home">
13 <div>
14 我是主页
15 </div>
16 </template>
17 <template id="blog">
18 <div>
19 我是博客
20 </div>
21 </template>
22 <template id="login">
23 <div>
24 <input type="text">
25 <input type="text">
26 <input type="button" value="登录" @click="login">
27 </div>
28 </template>
29 <template id="uquit">
30 <div>
31 <h3>是否<a style="color:red" @click ="uquit">退出</a></h3>
32 </div>
33 </template>
34 <template id="uapp">
35 <div>
36 <div>通过路由渲染下面对应导航组件</div>
37 <router-link to="/home">HOME</router-link>
38 <router-link to="/blog">BLOG</router-link>
39 <router-link to="/login">LOGIN</router-link>
40 <router-link to="/uquit">QUIT</router-link>
41 <router-view></router-view>
42 </div>
43 </template>
44 <script src="/node_modules/vue/dist/vue.js"></script>
45 <script src="/vue_router_use/node_modules/vue-router/dist/vue-router.min.js"></script>
46 <script>
47 // 2.组件使用模板,同时实现对应模板调用的事件
48 var Home={
49 template:`#home`,
50 }
51 var Blog={
52 template:`#blog`,
53 }
54 var Login={
55 template:`#login`,
56 methods:{
57 login(){
58 localStorage.setItem('user',{name:'aa',password:'11'});
59 this.$router.push('/blog')
60 }
61 }
62 }
63 var Uquit={
64 template:`#uquit`,
65 methods:{
66 uquit(){
67 localStorage.removeItem('user');
68 this.$router.push('/login')
69 }
70 }
71 }
72 var Uapp={
73 template:`#uapp`,
74 }
75 //3.允许在当前Vue创建路由
76 Vue.use({VueRouter})
77 //4.创建路由router
78 var router= new VueRouter({
79 //5、挂载需要通过路由渲染的对应组件,匹配规则--(引用组件可通过!!路由规则path或name来引用!!)
80 routes:[
81 {
82 path:'/home',
83 component: Home
84 },
85 {
86 path:'/blog',
87 component: Blog,
88 meta:{
89 auth:true
90 }
91 },
92 {
93 path:'/login',
94 component: Login
95 },
96 {
97 path:'/uquit',
98 component: Uquit
99 }
100
101 ],
102 })
103 //6.路由守卫判断路由组件之间的跳转,点击通过路由渲染的组件,
104 //如果将要跳转到的路由,路由规则的meta内的属性值为true,就要判断是否具备跳转条件,才跳转到此路由
105 router.beforeEach((to,from,next)=>{
106 if(to.meta.auth){
107 if(localStorage.getItem('user')){
108 next()
109 }else{
110 next('/login')
111 }
112 }else{
113 next()
114 }
115 })
116 //vue实例化
117 new Vue({
118 el:"#app",
119 template:"<Uapp/>",
120 router,
121 components:{Uapp}
122 })
123 </script>
124
125 </body>
126 </html>