废话不多说,直接上代码!
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>hello world</title> 7 <style type="text/css" media="screen"> 8 .child-view { 9 position: absolute; 10 width: 100%; 11 transition: all .8s cubic-bezier(.55, 0, .1, 1); 12 } 13 14 .slide-left-enter, 15 .slide-right-leave-active { 16 opacity: 0; 17 -webkit-transform: translate(500px, 0); 18 transform: translate(500px, 0); 19 } 20 21 .slide-left-leave-active, 22 .slide-right-enter { 23 opacity: 0; 24 -webkit-transform: translate(-500px, 0); 25 transform: translate(-500px, 0); 26 } 27 </style> 28 </head> 29 30 <body> 31 <div id="app"> 32 <div> 33 <!-- 4、<router-link>默认会被渲染成一个 `<a>` 标签 ,to指令跳转到指定路径 --> 34 <router-link to="/home">Go to Home</router-link> 35 <router-link to="/about">Go to About</router-link> 36 </div> 37 <!-- 5、在页面上使用<router-view></router-view>标签,用于渲染匹配的组件 --> 38 <transition :name="transitionName"> 39 <router-view class="child-view"></router-view> 40 </transition> 41 </div> 42 <!-- 组件 --> 43 <template id="Home"> 44 <div> 45 <h1> {{msg}}</h1> 46 </div> 47 </template> 48 <template id="About"> 49 <div> 50 <h1> {{msg}}</h1> 51 </div> 52 </template> 53 <!-- 0、引入依赖库 --> 54 <script src="https://cdn.bootcss.com/vue/2.3.4/vue.min.js"></script> 55 <script src="https://cdn.bootcss.com/vue-router/2.7.0/vue-router.min.js"></script> 56 <script type="text/javascript"> 57 /* 1、创建组件 */ 58 var Home = Vue.extend({ 59 template: '#Home', 60 data: function() { 61 return { 62 msg: 'Hello, vue router!' 63 } 64 } 65 }); 66 var About = Vue.extend({ 67 template: '#About', 68 data: function() { 69 return { 70 msg: 'This is the tutorial about vue-router.' 71 } 72 } 73 }); 74 75 // 2. 创建 router 实例,然后传 `routes`路由映射 配置 76 var router = new VueRouter({ 77 routes: [{ 78 path: '/home', 79 component: Home 80 }, { 81 path: '/about', 82 component: About 83 }, { 84 path: '/', 85 component: Home 86 } //设置默认路径 87 ] 88 }); 89 90 // 3. 创建和挂载根实例。记得要通过 router 配置参数注入路由,从而让整个应用都有路由功能 91 var vm = new Vue({ 92 data: { 93 transitionName: 'slide-left' 94 }, 95 router: router 96 97 }).$mount('#app'); 98 99 // 现在,应用已经启动了! 100 </script> 101 </body> 102 103 </html>