Vue前端路由 用前提醒: 在导入Vue路由钱,要先导入Vue,不然会报错 <script src="./lib/vue_2.5.22.js"></script> <script src="./lib/vue-router_3.0.2.js"></script> 1. 路由规则中,component只接收路由组件,不接收直接的字符串'<h1></h1>' 2. 最后要把路由实例对象挂载到Vue实例对象汇总 3.命名路由 <router-link :to="{ name: 'xm1'}">User3</router-link> to前面有: !!!!!!!!!!! 4.这样子App组件和重定向的User组件都会被渲染出来,因为User是App的子组件 {path:'/',component:App,redirect: '/user',children:[ {path:'/user',component:User},} 知识: 1.基本使用: 1.引入相关的库文件 2.添加路由链接 3.添加路由填充位 4.定义路由组件 5.配置路由规则并创建路由实例 6.把路由挂载到 Vue 根实例中 2.路由重定向:{path:'/', redirect: '/user'}, 3.嵌套路由用法 4.动态匹配路由的基本用法 1.动态路径参数 以冒号开头 <router-link to='/register/tab/1'>Tab1</router-link> {path:'/register/tab/:id',component:Tab,props:true}, Tab组件中 props:['id'], template:'<h1>Tab {{id}}</h1>' 或者: <router-link to='/register/tab/1'>Tab1</router-link> {path:'/register/tab/:id',component:Tab,props:{id:3,name:'小明'}}, props:['id','name'], 2.路由组件中通过$route.params获取路由参数 {path:'/register/tab/:id',component:Tab,props:route=>({name:'小明',id:route.params.id})}, 例子: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <!-- 导入 vue 文件 --> <script src="./lib/vue_2.5.22.js"></script> <script src="./lib/vue-router_3.0.2.js"></script> </head> <body> <div id='app'> <router-link to="/user">User</router-link> <router-link to='/register'>Register</router-link> <router-link :to="{ name: 'xm1'}">User3</router-link> <router-view></router-view> </div> <script type="text/javascript"> const User = { template:` <div> <h1>User组件</h1> <button @click='fn'>跳到re</button> <button @click='fn1'>前进</button> </div>`, methods:{ fn:function () { // body... this.$router.push('/register') }, fn1:function () { // body... this.$router.go(1) } } } const Register = { template:` <div> <h1>Register</h1> <button @click='fn'>返回</button> </div>`, methods:{ fn:function () { // body... this.$router.go(-1) } } } var router = new VueRouter({ routes:[ {path:'/' ,redirect:'/user'}, {path:'/user',name:'xm1',component:User}, {path:'/register',name:'xm2',component:Register} ] }) const vm = new Vue({ el: '#app', data:{ }, router:router }) </script> </body> </html>