1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="utf-8"> 6 <meta name="viewport" content="width=device-width,initial-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>Document</title> 9 <!--导入Vue的包--> 10 <script src=" https://cdn.jsdelivr.net/npm/vue"></script> 11 <!-- 1.导入包 --> 12 <script src="../lib/vue-router-3.0.6.js"></script> 13 </head> 14 15 <body> 16 <div id="app"> 17 <router-link to="/login">登录</router-link> 18 <router-link to="/register">注册</router-link> 19 20 <!-- 容器 --> 21 <router-view></router-view> 22 23 </div> 24 25 <script> 26 //2.创建子组件 27 var login={ 28 template:'<h3>这是登录子组件,这个组件是 江小白 开发的。</h3>' 29 } 30 31 var register={ 32 template:'<h3>这是注册子组件,这个组件是 白小江 开发的。</h3>' 33 } 34 35 //3.创建一个路由对象 36 var router=new VueRouter({ 37 routes:[//路由规则数组 38 {path:'/',redirect:'/login'}, 39 {path:'/login',component:login}, 40 {path:'/register',component:register} 41 ], 42 linkActiveClass:'myactive' //和激活相关的类 43 }) 44 45 46 //创建 Vue 实例,得到 ViewModel 47 var vm = new Vue({ 48 el:'#app', 49 data:{ }, 50 methods:{ }, 51 // router:router 52 router, 53 watch:{ 54 //this.$route.path 55 '$route.path':function(newVal,oldVal){ 56 // console.log(newVal + ' --- ' +oldVal) 57 if(newVal==='/login'){ 58 console.log('欢迎进入登录页面') 59 }else if(newVal==='/register'){ 60 console.log('欢迎进入注册页面') 61 } 62 } 63 } 64 }); 65 </script> 66 </body> 67 </html>