首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Vue路由详解(路由基础,路由轮播,路由传参,通配符路由)

Vue路由详解(路由基础,路由轮播,路由传参,通配符路由)

作者头像
生南星
发布2019-07-22 14:33:11
3K0
发布2019-07-22 14:33:11
举报
文章被收录于专栏:生南星生南星

一. Vue路由基础知识点: 1.router-view: 类似angular里的插座,用于承载路由的切换组件 2.router-link: 类似angular里的routerLink,区别是:vue的router-link是一个组件,直接充当a标签使用.但是在最后渲染时,vue还是会将其渲染成a标签 3.routes: 数组,用来做路由信息的配置 4.router: 对象,通过该对象的方法实现路由的跳转,例如按钮点击实现跳转 5.route: 类似angular里的ActiveRoute,用来获取路由传参的值

组件的创建和切换:

a.在组件里写router-link标签,绑定to属性,to属性是一个对象,path属性里是当前组件的路由路径

例:

<!--通过router-link进行路由导航-->
<router-link :to="{path:'/home'}">首页</router-link>

b.不需要切换的组件(例如头组件和尾组件)直接以标签的形式写在APP(根)组件里,记得注册和引入.

要切换的组件在根组件里挖一个坑<router-view></router-view>,然后在index.js里的routes数组中配置路由信息,每个路由都是一个对象,每个对象里都有两个最基本的属性:path和component

例:

根组件(App.vue)

<template>
  <div id="app">
    <MyHeader></MyHeader>
    <router-view></router-view>
    <MyFooter></MyFooter>
  </div>
</template>

<script>
  import MyHeader from './components/MyHeader';
  import MyFooter from './components/MyFooter';
  
export default {
  name: 'App',
  components:{
    MyHeader,
    MyFooter
  }
}
</script>

<style>

</style>

index.vue:

routes: [
    //一级路由配置
    {path:'/home',component:Home},
]

c.路由重定向是 redirect

一级路由重定向, 例:

重定向也是通过routes配置来完成,下面的例子是从 / 重定向到 /home:

routes: [
    //路由重定向
    {path:'/',redirect:'/home'},
]

二级路由重定向

二级路由的注意点: 子路由里的path时基于mine的,不要加 / ,加了 / 就是基于跟路由的

a. 重定向的目标可以是一个命名路由: (常用)

redirect的值是一个对象.

routes: [
    {path: '/mine',component:Mine,children:[
        //子路由里的path时基于mine的,不要加 / ,加了 / 就是基于跟路由的
        //二级路由的重定向
        {path:'',redirect: {path:'account',query:{userName:'宇智波带土',passwd:'999'}}},
      ]},
]

b. 重定向的目标可以是一个方法,动态返回重定向目标:

redirect的值是一个函数.

routes: [
    {path: '/a',component:Mine,children:[
        //子路由里的path时基于mine的,不要加 / ,加了 / 就是基于跟路由的
        //二级路由的重定向
        {path:'',redirect: to => {
          //方法接收  目标路由   作为参数
          //return 重定向的 字符串路径/路径对象
        }}},
      ]},
]

三. 组件的轮播

1.swiper--组件轮播

<template>
    <div class="home">
      <h1>这是Home组件</h1>
      <div class="swiper-container">
        <div class="swiper-wrapper">
          <div class="swiper-slide" v-for="(item,index) in bannerArr" :key="index">
            <img :src="item" alt="">
          </div>
        </div>
        <!-- 如果需要导航按钮 -->
        <div class="swiper-button-prev"></div>
        <div class="swiper-button-next"></div>
      </div>
    </div>
</template>

<script>
  import Swiper from 'swiper';
    export default {
        name: "Home",
        data(){
          return {
            bannerArr:[
              "https://place-hold.it/600x300",
              "https://place-hold.it/600x301",
              "https://place-hold.it/600x302",
              "https://place-hold.it/600x303",
              "https://place-hold.it/600x304",
            ]
          }
        },
        mounted(){
          // console.log(Swiper)
          new Swiper ('.swiper-container', {
            direction: 'horizontal', // 水平切换选项
            loop: true, // 循环模式选项
            // 如果需要前进后退按钮
            navigation: {
              nextEl: '.swiper-button-next',
              prevEl: '.swiper-button-prev',
            },
          })
        }
    }
</script>

<style scoped>
  @import "../../node_modules/swiper/dist/css/swiper.min.css";
  .home{
    width: 100%;
    height: 70%;
    background-color: #afff7c;
  }
  .swiper-container{
    width: 600px;
    height: 300px;
    margin: 0 auto;
  }
  .swiper-slide{
    width: 100%;
    height: 100%;
    font-size: 30px;
    text-align: center;
    line-height: 300px;
  }
</style>

2. vue-awesome-swiper--vue的轮播

a. 安装插件

npm i vue-awesome-swiper -S

b. 全局引入或者组件引入

//全局引入
import vueSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'  //引入样式
 Vue.use(vueSwiper, /* { default global options } */)
 
 //组件引入
import { swiper, swiperSlide } from "vue-awesome-swiper";
require("swiper/dist/css/swiper.css");
components: {
swiper,
swiperSlide
};

c. 使用,一班组件的用法

<swiper :options="swiperOption">
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
      <swiper-slide><img src="static/images/jay.jpg"></swiper-slide>
    </swiper>
    <!--以下看需要添加-->
    <div class="swiper-scrollbar"></div> //滚动条
    <div class="swiper-button-next"></div> //下一项
    <div class="swiper-button-prev"></div> //上一项
    <div class="swiper-pagination"></div> //标页码
 data(){
    return{
      swiperOption: {//swiper3
      autoplay: 3000,
      speed: 1000,
      }
    }
  }

d. 配置

下面只放一些简单地配置

1)按钮



navigation: {
    nextEl: '.swiper-button-next', //前进按钮的css选择器或HTML元素。
    prevEl: '.swiper-button-prev', //后退按钮的css选择器或HTML元素。
    hideOnClick: true, //点击slide时显示/隐藏按钮
    disabledClass: 'my-button-disabled', //前进后退按钮不可用时的类名。
    hiddenClass: 'my-button-hidden', //按钮隐藏时的Class
   },

2) 分页器

pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
    //type: 'fraction',
    //type : 'progressbar',
    //type : 'custom',
    progressbarOpposite: true, //使进度条分页器与Swiper的direction参数相反
    bulletElement : 'li', //设定分页器指示器(小点)的HTML标签。
    dynamicBullets: true,  //动态分页器,当你的slide很多时,开启后,分页器小点的数量会部分隐藏。
    dynamicMainBullets: 2, //动态分页器的主指示点的数量
    hideOnClick: true, //默认分页器会一直显示。这个选项设置为true时点击Swiper会隐藏/显示分页器。
    clickable: true, //此参数设置为true时,点击分页器的指示点分页器会控制Swiper切换。
  },

3) 滚动条

 scrollbar: {
     el: '.swiper-scrollbar',
     hide: true, //滚动条是否自动隐藏。默认:false,不会自动隐藏。
     draggable: true, //该参数设置为true时允许拖动滚动条。
     snapOnRelease: true, //如果设置为false,释放滚动条时slide不会自动贴合。
     dragSize: 30, //设置滚动条指示的尺寸。默认'auto': 自动,或者设置num(px)。
   },

附上自己写的代码:

<template>
    <div class="product">
      <h2>这是Product组件</h2>
  
      <swiper :options="swiperOption" class="lb">
        <swiper-slide v-for="(item,index) in bannerArr" :key="index">
          <img :src="item">
        </swiper-slide>
      </swiper>
      <!--以下看需要添加-->
      <!--滚动条-->
      <!--<div class="swiper-scrollbar"></div>-->
      <!--下一项-->
      <div class="swiper-button-next"></div>
      <!--上一项-->
      <div class="swiper-button-prev"></div>
      <!--标页码-->
      <div class="swiper-pagination"></div>
      
    </div>
</template>

<script>
    export default {
        name: "Product",   
        data(){
          return{
            swiperOption: {//swiper3
              autoplay: 3000,
              speed: 1000,
              loop:true,
              pagination: {
                el: '.swiper-pagination',
                type: 'bullets',
                progressbarOpposite: true, //使进度条分页器与Swiper的direction参数相反
                bulletElement : 'li', //设定分页器指示器(小点)的HTML标签。
                dynamicBullets: true,  //动态分页器,当你的slide很多时,开启后,分页器小点的数量会部分隐藏。
                dynamicMainBullets: 2, //动态分页器的主指示点的数量
                hideOnClick: true, //默认分页器会一直显示。这个选项设置为true时点击Swiper会隐藏/显示分页器。
                clickable: true, //此参数设置为true时,点击分页器的指示点分页器会控制Swiper切换。
    
              },
              navigation: {
                nextEl: ".swiper-button-next", //前进按钮的css选择器或HTML元素。
                prevEl: ".swiper-button-prev", //后退按钮的css选择器或HTML元素。
              },
            },
            bannerArr:[
              "https://place-hold.it/800x400",
              "https://place-hold.it/800x401",
              "https://place-hold.it/800x402",
              "https://place-hold.it/800x403",
              "https://place-hold.it/800x404",
            ]
          }
        }
    }
</script>

<style scoped>
  .product{
    width: 100%;
    height: 75%;
    background-color: #5fd1ff;
  }
  .lb{
    width: 800px;
    height: 400px;
    /*background-color: red;*/
    margin: 0 auto;
  }
  .swiper-pagination{
    margin-left: 50%;
    margin-top: 10px;
  }
</style>

参考博客:

https://blog.csdn.net/dwb123456123456/article/details/82701740

https://segmentfault.com/a/1190000014609379

二. 路由传参 1.通过query查询参数传参

内容组件接收头组件传来的参数--query方式传递来的参数存储在router对象里,使用this.$route方式获取该对象

MyHeader组件:

<!--使用query传参,不需要配置路由-->
<router-link :to="{path: '/product',query:{q_proName:'西瓜',q_proPrice:20}}">商品展示</router-link>

Product组件:

<template>
    <div class="product">
      <h2>这是Product组件</h2>
      <p>{{getQuery}}</p>
    </div>
</template>

<script>
    export default {
        name: "Product",
        computed:{
          getQuery(){
            //query方式传递来的参数存储在router对象里,使用this.$route方式获取该对象
            return `商品名字是:${this.$route.query.q_proName},商品价格是:${this.$route.query.q_proPrice}`;
          }
        }
    }
</script>

<style scoped>
  .product{
    width: 100%;
    height: 70%;
    background-color: #5fd1ff;
  }
</style>

2.根据params路径参数传参 -- 需要配置路由 vue里的params传值只能用name不能用path -- params方式传递来的参数存储在router对象里,使用this.$route方式获取该对象

传递的值以路径的形式拼接在网址的后面. 注意:在使用该方式是params的key,路径配置的key,取值的key,三者保持一致

<router-link :to="{name:'pro',params:{userId:'12326',youId:'4699'}}">商品展示</router-link>

//计算属性
computed:{
          getParams(){
            // console.log(this.$route.params);
            return `用户的id是:${this.$route.params.userId},游客的id是:${this.$route.params.youId}`;
     }
},

//配置路由信息
{path: '/product/:userId/:youId',component: Product,name:'pro'},

按钮的params传参:

<button @click="shopCartClick">我的购物车</button>

//计算属性
computed:{
      shopCartClick(){
          //借助router对象实现路由的切换
          // this.$router.push({path:"/mine/shopcart"});
          //这里回有波浪线提示,转化为json串能解决问题,不转化也不错
          // this.$router.push({name:'sc',params:{proName:'雨伞',proPrice:20}});
          this.$router.push({name:'sc',params:{pro:JSON.stringify([{proName:'雨伞',proPrice:20}])}});
     }
},

//页面接收
//1.没有装化为json串时
computed:{
          getPro(){
            return `商品名称:${this.$route.params.proName}, 商品价格:${this.$route.params.proPrice}`;
          }
}
//2.转化为json字符串时,计算属性不一样,页面模板也需要改变
computed:{
          getPro(){
            let arr = JSON.parse(this.$route.params.pro);
            return arr;
    }
}
//页面模板
<p v-for="pro in getPro">
   <span>商品名称:{{pro.proName}}, 商品价格:{{pro.proPrice}}</span>
</p>

//配置路由信息
{path:'shopcart/:proName/:proPrice',component:ShopCart,name:'sc'},

三. 通配符路由

//通配符路由
{path:'*',redirect:'/home'},

用到更多:

style标签里的scoped属性表示当前样式只对该组件起效果,不加的话样式变成全局样式(Vue)

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-04-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 生南星 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档