路由和线路
路由router
表示当前项目全局的路由实例对象
跳转方法:push,replace,go,back
线路route
表示当前路由页面的信息对象
获取动态路由的参数:params
router跳转的两种方式
js跳转叫[编程式跳转]
<button @click="fn_target"></button>
fn_target(){this.$router.push('/home')
}
标签跳转叫【声明式】
<router-link to="/name"></router-link>
router-link
特性 默认是会被渲染成a标签 可以用tag属性修改
属性值
- to属性跳转到哪个页面和path对应 (相当于执行一次this.$router.push(’/name’))
- replace属性,不需要写值,让页面不可回退,默认是push属性
- active-class用于修改单个class属性
- tag渲染成什么元素
router-view
router-view决定渲染组件位置
routes简单语法
【注意】:不要忘记引入组件
const routes = [{path: '',// redirect重定向 ,相当于直接默认了home页面redirect: '/home'},{path: ' * ',// 当访问组件不存在时默认返回home组件redirect: '/home'},{//路由嵌套(也需要一个视口) 地址显示为 /home/name//【注意】子路由路径中不加 / 程序自动拼接path: '/home',component: Home,children: [//重定向{ path: '', redirect: 'new' },{path: 'new',component: New,},{path: 'product',component: Product,}]},{//动态路由path: '/User/:userId',//渲染时:this.$router.push(`/info/value`)component: User},// 路由懒加载(不用引入组件) 分割js文件(一个懒加载对应一个js文件),避免用户加载页面会出现短暂空白//方式一:结合Vue异步组件和webpack的代码分析(知道即可,老项目有可能会出现)//const Home = resolve => { require.ensure(['../components/Home.vue],()=>{//resolve(require('../components/Home.vue')) })}//方式二:AMD写法//const About = resolve =>require(['../components/About.vue'],resolve)//方式三:在ES5中,我们可以有更加简单的写法来组织Vue异步组件和Webpack的代码分割{ path: '/home',component: ()=>import('../components/Home')} ]
router简单使用
const router = new VueRouter({routes,// 默认hash值,现在改成history模式mode: 'history',// 修改全局的classlinkActiveClass: 'active'
})
路由传参的两种方式
params
- 隐式(不推荐) 静态路由使用params传参,地址栏不会带参数,所以刷新页面数据会丢,一般不使用
- 显示-动态路由传参。且必须使用路由命名的name属性,不可以使用path。使用params对象传递参数
//映射id this.id=>this.$route.params.id
props:['id']this.$router.push({name:'home',params:{id:1}})// routes配置中要有相应的name
const routes = [{// 动态路由等于params显示传参name: 'home', //给当前路由起一个名字,所以叫命名路由path: '/a/:id,component: () => import('./A.vue'),// props解耦,让组件的props解耦params参数(默认是false),可以简化语法props: true},
]
query
使用query传参,地址栏以get请求参数的形式表现。他没有动态路由优雅
// routes配置中要有相应的path
this.$router.push({path:'/home',query:{id:1}})