Vue路由vue-router
vue 路由
vue-router2
注意:vue-router2@2.x只适用于Vue2.x版本
安装
因为之前在安装vue-cli的时候选项中就包括了vue路由这一项是否yes or no安装,所以如果要单独安装可以参考下面
1.你也可以用<script src="../js/vue-router.js"></script>引入这种方式,但一般用倾向于用webpack模块化的方法
2.npm install vue-router@2.7.0 --save-dev,为了让package.json中打上一个log,后面加上--save-dev
如果在一个模块化的工程中使用,必须通过Vue.use()明确的安装路由功能,例如
import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter)
如果使用全局的script标签,则无需如此(手动安装)
重定向
重定向也是通过routes配置来完成,下面就是/a到/b
const router = new VueRouter({ routes:[{ path:'/a',redirect:'/b' }] })
重定向也可以是命名的路由,
const router = new VueRouter({ routes:[{ path:'/a',
name:'foo',
redirect:{name:'foo'} }] })
或者一个方法
const router = new VueRouter({ routes:[{ path:'/a',redirect:to=>{ //方法接收 目标路由 作为参数 //return 重定向 字符串路径或者路径对象 } }] })
在template标签中,可以使用标签router-link进行跳转到相应的vue组件
<router-link to="/card">card</router-link>
或者js methods方式跳转,这里是一个示例,可以结合下面的动态路由匹配一起进行
import router from '../router';//这里/index.js可以省略不用写。
handleClick:function(index){ //你需要router引用进来,才能进行跳转 router.push(`/card/detail/${index}`);//es6反向引号写法, }
动态路由匹配
点击事件
handleClick:function(index){
//你需要router引用进来,才能进行跳转
router.push(`/card/detail/${index}`);//es6反向引号写法,
}
占位id符号: path:'/card/detail/:id',前后两个id命名要匹配,否则无法接收到id值
接收id值: {{$route.params.id}},
src文件夹下面的components文件下的card.vue组件的代码
<template> <div> 我是card页面 <ul> <li v-for="(data,index) in datalist" @click="handleClick(index)">{{data}}</li> </ul> <router-view></router-view> </div> </template> <script> import router from '../router';//这里/index.js可以省略不用写。 export default { name:'card', data(){ return { datalist:['card1','card2','card3',] }; }, methods: { handleClick:function(index){ //你需要router引用进来,才能进行跳转 router.push(`/card/detail/${index}`);//es6反向引号写法, } }, } </script> <style> li{list-style: none;cursor: pointer;;} </style>
在需要接收传过来的动态参数的detail界面的代码
<template> <div> detail界面{{$route.params.id}}这里是接收详细按钮传过来的id值 </div> </template> <script> export default { name:'detail', } </script> <style> </style>
在src文件夹下面的router文件夹的index.js文件的routes添加路径,子组件,并且引用所有文件的路径
import Film from '@/components/film'
import Card from '@/components/card'
import Home from '@/components/home'
import NowPlaying from '@/components/nowplaying'
import ComingSoon from '@/components/comingsoon'
import Detail from '@/components/detail'
......
{ path:'/card', component:Card, children:[ { path:'/card/detail/:id',//动态路由匹配的写法/:id这里只起到占位的作用,也可以添加多个占位符 component:Detail } ] },
HTML5 history模式
export default new Router({ mode:'history', })
vue-router默认hash模式--使用URL的hash来模拟一个完整的URL,于是当URL改变时,页面不会重新加载。
如果不想要很丑的hash模式,我们也可以用路由的history模式,这种模式充分利用history.pushState API来完成URL的跳转无须重新加载页面,
在index.js下面的router下面加入mode:'history',这样就去掉了地址栏中的#符号,
不过这种模式要玩好,还需要后台的配置支持,因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问http://oursite.com/user/id就会跳出404,这样的体验就不好了。
所以呢,你要在服务器端增加一个覆盖所有情况的候选资源:如果URL匹配不到任何的静态资源,则应该返回同一个index.html页面,这个页面就是你app依赖的页面。

浙公网安备 33010602011771号