vue-rouer 路由
安装/配置:
//进入项目目录:(在搭建项目的时候安装了)
cnpm install vue-router --save
旧版路由
需要自己配置
//项目中载入,一般在main.js中载入:import VueRouter from 'vue-router'Vue.use(VueRouter)let router = new VueRouter({}) //其中配置路径和地址//在Vue中引入:new Vue({el: '#app',router,template: '<APP/>',components: { APP }})
新版路由:
自动配置好了,直接在router/index.js中设置即可
设置页面路由
一个vue页面
<template><div class="apple">213124</div>
</template>
<script>
export default {name: 'Apple'
}
</script>
<style scoped>
</style>
旧版
在new VueRouter({})所在页面引入:
import Apple from '@/components/Apple'routes: [mode:'history',{path:'/apple',component:Apple},{path:'/apple2',component:Apple2}]
新版
方法1:
const all = r => require.ensure([], () => r(require('../components/attendance/a_all')));
方法2:
const Login = (resolve) => {require(['@/components/Login/login'],resolve)};{path: '/hdwrj',name: 'hdwrj',component: hdwrj}
在APP.vue中引入
(会在这里显示)
<router-view></router-view>
路由定义
路由命名
{path:'/apple',component:Apple,name:'applePage'}
访问:<router-link :to="{name:'applePage'}">to apple</router-link>
命名路由视图
在router-view 上添加name
<router-view name='viewA '></router-view>
路由表中可以根据name定义页面
{path:'/apple',component:{viewA:Apple,viewB:OtherApple,},name:'applePage'}
路由嵌套(子路由)
{path:'/apple',component:Apple,childdren:[{path:'/childapple/',component:ChildApple}]},
内容要在Apple.vue中添加
<router-view></router-view>
页面跳转:
路由跳转
页面内跳转router-link
要在 mode:'history'
, 之下
<router-link :to="{path:'apple'},query: {id:id}">to apple</router-link><router-link :to="{path:'apple2'}">to apple2</router-link>普通页面跳转<router-link :to="{path:'apple'}">to apple</router-link>
基于当前路径跳转<router-link :to="'apple'">to apple</router-link>
根目录:<router-link :to="'/apple'">to apple</router-link>
动态设置:<router-link :to="apple">to apple</router-link>在data中:data(){reurn{apple:'apple'}}
传递参数:<router-link :to="{path:'apple',param:{color:'red'}}">to apple</router-link>可以访问 apple/red(参数)
改变router-link显示样式:<router-link :to="'apple'" tag="li">to apple</router-link>
在链接中设置参数
可以设置多层/apple/:color/:font/....
路由设置:path:'/apple/:color',
页面跳转:http://localhost:8080/apple/red
获取参数:$route.params.color
在?中的参数:query
路由:
{path:'/voucher',name: 'voucher',component: voucher
}传参:
this.$router.push({path:'/xxx',query:{id:id}
})接收参数:
this.$route.query.id
注意:传参是this.$router,接收参数是this.$route,这里千万要看清了!!!
$router
为VueRouter实例,想要导航到不同URL,则使用$router.push方法$route
为当前router跳转对象,里面可以获取name、path、query、params等
在json中的参数:params
路由:
{path: '/startWh',name: 'startWh',component: startWh
}
传参:
this.$router.push({name:'xxx'params:{id:id}
})接收参数:
this.$route.params.id
注意:params传参,push里面只能是 name:'xxxx',不能是path:'/xxx',因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!
query和params区别
- query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,
- params相当于post请求,参数不会再地址栏中显示
js中定义导航,跳转
router.push('apple') //或 {path:'apple'}
或
this.$router.push('/login');
路由重定向
比如默认页面是具体的某一个页面,比如访问根目录,会自动跳转到Apple.vue目录
{path:"/",redirect:'/apple'},
页面跳转–过渡
<transition name='fff'><keep-alive><!--缓存--><router-view></router-view></keep-alive></transition>