vue-router

一、vue-router使用

官网API:https://router.vuejs.org/zh-cn/

vue-router的本质是对浏览器history的封装。router改变的也就是浏览器的history。

  • history.go(0)刷新;
  • history.go(-1)倒退;
  • history.go(1)前进;
  • history.pushState('desc','test','/admin')  => 向浏览器添加一个状态,例加载localhost:8080/admin

1.安装

npm install vue-router

2.使用

1 import VueRouter from 'vue-router'
2 Vue.use(VueRouter);

3.布局(html)

<!-- 使用 router-link 组件来导航;通过传入 `to` 属性指定链接. -->
<router-link to="/home">主页</router-link>
<!-- 路由出口;路由匹配到的组件将渲染在这里 -->
<router-view></router-view>

布局扩展说明:

 1 <router-link to="/home" tag="li" active-class="active">
 2       <a href="javascript:;">首页</a>
 3 </router-link>
 4 <!-- router-link编译成a标签,加上tag='li',编译成li标签 -->
 5 <!-- 改变选中的class类名:默认是 router-link-active
 6                        1、active-class
 7                      2、const router=new VueRouter({
 8                              linkActiveClass: 'active'
 9                        }); -->
10  
11 <keep-alive> 
12      <router-view  class="router-view"></router-view>
13 </keep-alive>
14 <!-- keep-alive标签保留路由状态避免重新渲染,即内容有了就不需要重新加载了 -->        

4.路由具体写法(javascript)

// 定义路由组件
const Home={template:'<h3>我是主页</h3>'};
const News={template:'<h3>我是新闻</h3>'};

// 定义路由,每个路由应该映射一个组件
const routes=[
     {path:'/home', component:Home},
     {path:'/news', component:News}
];

// 生成路由实例
const router=new VueRouter({
      routes    // (缩写)相当于 routes: routes
});

// 最后挂载到vue上
new Vue({
      router
});
// 重定向 -即设置默认显示的组件
{path:'*', redirect:'/home'}

二、vue-router配置

1、一般的vue项目链接localhost:8080/#/goods/sdf89/user/admin链接中会有一个#号,这是router构造配置。

const router = new VueRouter({ 
      mode: 'hash', (默认值)
      routes: [...] 
})
要去掉#,使用浏览器正常的链接访问需要设置
const router = new VueRouter({ 
      mode: 'history', 
      routes: [...] 
}

2、滚动位置配置

const router = new VueRouter({
     scrollBehavior: () => ({ y: 0 })  // 滚动条滚动的行为,不加这个默认就会记忆原来滚动条的位置
});

三、进阶

watch:{
    $route(to,from){         //监听路由变化
        console.log(to.path);
... } }

四、router基础分类

1、动态路由配置

除了 $route.params 外,$route 对象还提供了其它有用的信息,例如,$route.query(如果 URL 中有查询参数)、$route.hash 等等。你可以查看 API 文档 的详细说明。

例:

>> router/index.js :

export default new Router({
    routes:[
        {
            path:'/goods/:goodsId',
            component: GoodsList
        }
    ]
})


>> GoodsList.vue :

<template>
    <div>
        <span>{{$route.params.goodsId}}</span>
    </div>
</template>

网址:localhost:8080/#/goods/sdf89  => $route.params.goodsId输出sdf89
{
   path:'/goods/:goodsId/user/:name',
   component: GoodsList
}

网址:localhost:8080/#/goods/sdf89/user/admin

<span>{{$route.params.goodsId}}</span>   =>     sdf89
<span>{{$route.params.name}}</span>     =>  admin

2、嵌套路由

// # 不是一级路径,链接要写绝对地址,不能直接写'/title'
<router-link to='/goods/title'></router-link>

export default new Router({
    routes:[
        {
            path:'/goods',
            name:'GoodList',
            component: GoodsList,
            children:[
                {
                    path:'title',  // 不能'/title'加了/就变成了一级路径
                    name:'title',
                    component:Title
                 },
                {
                    path:'img', 
                    name:'img',
                    component:Image
                 }
            ]
        }
    ]
})

3、编程式路由--通过js实现页面的跳转

  • $router.push('name') 
  • $router.push({path:'name'})
  • $router.push({path:'name'?a=123})或者$router.push({path:'name',query:{a:123}})
  • $router.go(1)
<button @click="jump">button-跳转到购物车页面</button>
methods:{
    jump(){
        this.$router.push('cart');       // 第一种:跳转到cart页面了
        this.$router.push({ path : '/cart' });     // 第二种
        this.$router.push({ path : '/cart?goodsId=123' });    // 第三种
        this.$router.go(-2);  // 倒退两步
    }
}

Cart.vue:
// 若第三种跳转(带参数)
<span>{{$route.query.goodsId}}</span>   =>输出123


router/index.js:
export default new Router({
    routes:[
        {
            path:'/cart',
            component: Cart
        }
    ]
})

4、命令路由和命名视图

  ————给路由定义不同的名字,根据名字进行匹配;
  ————给不同的router-view定义名字,通过名字进行对应组件的渲染;

(1)/命名路由/

One:
<router-link v-bind:to="{name: 'cart'}"></router-link>

export default new Router({
    routes:[
        {
            path:'/cart',
            component: Cart
        }
    ]
})

Two:
<router-link v-bind:to="{name:'cart', params:{cardId: 123}}"></router-link> <!-- params 是路由的参数 -->

export default new Router({
    routes:[
        {
            path:'/cart/:cardId',  // 带参数
            component: Cart
        }
    ]
})

(2)/命名视图/

<router-view class="main"></router-view>
<router-view class="left" name="title"></router-view>
<router-view class="right" name="img"></router-view>

export default new Router({
    routes:[
        {
            path:'/',  // 带参数
            components: {
                default:GoodList,
                title: Title,   // 对应Title组件
                img: Image
            }
        }
    ]
})

可以定义class类名写样式:
.left,.right{float:left;49%;border:1px solid gray;}
原文地址:https://www.cnblogs.com/ccyinghua/p/7841237.html