前端路由和 VueRouter

前端路由

核心:

改变url,但页面不进行整体的刷新,即不向后台发请求

如何实现
  1. 通过修改hash方式实现
  • location.hash
  1. 通过H5中的history实现
history.pushState(data, title, url); //这种方式可以返回之前的页面

history.replaceState(data, title, url); //这种方式无法返回之前的页面,相当于替换

history.go() //通过传入数字进行跳转,数字可为正可为负,为0时相当于调用,即刷新当前页面
history.forward() 相当于 history.go(1)
history.back() 相当于 history.go(-1)
//这三个接口相当于浏览器界面的前进后退键

VueRouter

安装

npm install vue-router --save

引入并使用
//index.js
import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
设置路由
//index.js

//引入组件
import Home from '../components/Home'
import About from '../components/About'

//定义路由,每个路由对应一个组件
const routes = [
    {path: '/', redirect: '/home'}, //重定向路由,默认展示Home组件
    {path: '/home', component: Home},
    {path: '/about', somponents:About}
]

//创建router实例
const router = new VueRouter({
    routes,
    mode: 'history', //可以将默认的hash模式转换成history模式,使导航栏更美观
    linkActiveClass: 'active' //设置活跃class属性,点击某个路由会添加该class名,显示对应的css效果
})

//暴露router实例
export default router
实现路由跳转
//App.vue

//在根组件中设置
<template>
    <div id='app'>
        <router-link to='/home'>首页</routet-link>
        <router-link to='/about'>关于</routet-link>
        <router-view></router-view>
    </div>
</template>
  1. 通过点击 router-link 实现路由跳转,router-link 默认渲染成 <a></a> 标签,可以通过设置 tag 属性渲染成其它标签,如 button、div 等等
  2. router-link 中设置 replace 属性,可将默认的 history.pushState 转换成 history.replaceState
  3. router-view 表示跳转到的组件的显示位置,所有页面的公共部分写在根组件 App.vue
编程式路由导航

通过普通标签实现路由跳转

//App.vue

<template>
    <div id='app'>
        <button @click='homeClick'>首页</button>
        <button @click='aboutClick'>关于</button>
        <router-view></router-view>
    </div>
</template>

<script>
    name: 'App',
    methods: {
        homeClick(){
            this.$router.push('/home') //history.pushState()方法
        },
        aboutClick(){
            this.$router.replace('/about') //history.replaceState()方法
        }
    }
</script>
动态路由

动态路由参数使用冒号:标记,当匹配到对应的路由时,参数值会被设置到 this.$route.params 中,可在每个组件内使用

//index.js

const routes = [
    {path: '/user/:userId', component: User} //动态路由参数以冒号:开头
]
//App.vue

<template>
    <div id='app'>
        <router-link to='/home'>首页</router-link>
        <router-link to='/about'>关于</router-link>
        <!--通过把userId绑定到to属性中,可跳转至对应用户的界面-->
        <router-link :to="'/user/' + userId">用户</router-link> 
        <router-view></router-view>
    </div>
</template>

<script>
    export default {
        name: 'App',
        data(){
            return{
                userId: 'jack'  //这里用于接收后台传过来的数据
            }
        },
    }
</script>

通过 $route.params.userId 可以得到 userId 的值

//User.vue

<template>
    <div>
        <p>userId: {{userId}}</p>
    </div>
</template>

<script>
    export default {
        name: 'User',
        computed: {
            userId(){
                return this.$route.params.userId
            }
        }
    }
</script>
路由懒加载

概念: 当打包构建应用时,JS包会变得非常大,影响页面加载,影响用户体验。
所以我们把不同路由对应的组件分割成不同的代码块,当访问某个路由时,再加载该路由对应的组件,这样就提高了效率

实现: 只需修改引入组件时的代码

//index.js

//引入组件,首页一般不需要懒加载
const About = () => import('../components/About')
const User = () => import('../components/User')
路由嵌套

首先在index.js文件中,注册子组件和配置子路由

// index.js

const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')

const routes = [
    {
        path: '/', 
        redirect: '/home'   //重定向路由,默认展示Home组件
    }, 
    {
        path: '/home', 
        component: Home,
        children: [         //嵌套路由,又称子路由
            {path: '/', redirect: 'news'},
            {path: 'news', component: HomeNews},
            {path: 'message', component: HomeMessage}
        ]   
    },
    {
        path: '/about', 
        somponents:About
    }
]

然后在Home.vue文件中,展示子组件

<template>
  <div id="home">
      <h2>我是首页</h2>
      <router-link to='/home/news'>新闻</router-link>
      <router-link to='/home/message'>消息</router-link>
      <router-view></router-view>
  </div>
</template>
路由传参

一、params类型,即动态路由传参

  • 配置路由格式:/router/:id
  • 传递方式:在path后面加上要传的值
  • 传递后形成的路径:/router/user1/router/user2

二、'query’类型

  • 配置路由格式:/router,即普通配置方式
  • 传递方式:对象中使用querykey作为传递方式
  • 传递后形成的路径:/router?id=123/router?id=abc

在跳转路由的文件中,以对象的方式绑定要传的值

<!--query路由传参--> 
<router-link :to="{path: '/profile', query: {name: 'starl', age: 18}}">档案</router-link> 

通过$route.query.attribute取值

// Profile.vue文件

<p>{{$route.query.name}}</p>
<p>{{$route.query.age}}</p>

三、编程式路由导航怎么传参

//App.vue

<template>
    <div id='app'>
        <button @click='userClick'>首页</button>
        <button @click='profileClick'>档案</button>
        <router-view></router-view>
    </div>
</template>

<script>
    name: 'App',
    methods: {
        //params传参
        userClick(){
            this.$router.push('/user/' + this.userId)   //history.pushState()方法
        },
        //query传参
        profileClick(){
            this.$router.replace({
                path: '/profile',
                query: {
                    name: 'Starl',
                    age: 18
                }
            })   //history.replaceState()方法
        }
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值