Vue学习笔记(十) Vue Router

1、简介

Vue Router 是 Vue.js 的官方路由管理器,在官方文档中描述的功能包括:

  • 嵌套的路由/视图表
  • 模块化的、基于组件的路由配置
  • 路由参数、查询、通配符
  • 基于 Vue.js 过渡系统的视图过渡效果
  • 细粒度的导航控制
  • 带有自动激活的 CSS class 的链接
  • HTML5 history 模式或 hash 模式,在 IE9 中自动降级
  • 自定义的滚动条行为

这里,还是先附上官方文档的链接:https://router.vuejs.org/zh/

2、安装

(1)通过 CDN 引用

<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

(2)通过 NPM 安装与使用

  • 安装
> npm install vue-router
  • 使用

在项目中需要通过 Vue.use() 明确安装路由功能

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

3、入门

下面,我们用一个简单的例子来体会一下 Vue Router 的基本使用方法

首先创建一个命名为 index.html 的文件,然后在文件中输入如下代码(具体请看代码注释):

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello</h1>
        <p>
            <!-- 默认渲染成 <a> 标签,通过 to 属性指定路径 -->
            <router-link to="/home">Home</router-link> | 
            <router-link to="/about">About</router-link>
        </p>
        <!-- 路由匹配到的组件渲染到这里 -->
        <router-view></router-view>
    </div>

    <script>
        // 1、定义组件
        const Home = {
            template: `
                <div>
                    <h3>Home Page Here</h3>
                    <p>This is home page</p>
                </div>
            `
        }
        const About = {
            template: `
                <div>
                    <h3>About Page Here</h3>
                    <p>This is about page</p>
                </div>
            `
        }

        // 2、定义路由
        const routes = [
            {
                path: '/home', // 匹配的路径
                component: Home // 显示的组件
            },
            {
                path: '/about',
                component: About
            }
        ]

        // 3、创建 router 实例,传入 routes 配置
        const router = new VueRouter({
            routes // 缩写,相当于 routes : routes
        })

        // 4、创建并挂载根实例
        const app = new Vue({
            router // 注入路由
        }).$mount('#app')
    </script>
</body>

</html>

当我们打开页面时,URL 为 index.html#/

如果我们点击 Home,URL 跳转为 index.html#/home(此时,匹配路由 /home,显示组件 Home)

如果点击 About,URL 跳转为 index.html#/about(此时,匹配路由 /about,显示组件 About)

4、动态路由

下面考虑这样一个需求,我们要为路由 /user/Alice/user/Bob 指定使用同一个组件 User

再泛化一点来说就是为每一个不同的用户(路由为 /user/xxx)都指定使用同一个组件

这时候,动态路由就可以派上用场啦

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello</h1>
        <router-view></router-view>
    </div>

    <script>
        const User = {
            // 在模板中我们可以用 $route 对象中的 params 属性获得 URL 参数
            template: '<p>The user name is {{ $route.params.name }}</p>'
        }

        const routes = [
            {
                path: '/user/:name', // 以冒号开头表示参数,可以同时使用多个参数
                component: User
            }
        ]

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

</html>

这时候,我们手动输入 URL index.html#/user/Alice,页面会显示 The user name is Alice

如果再输入 index.html#/user/Bob,页面显示会变成 The user name is Bob

但是需要注意,从 /user/Alice 导航到 /user/Bob,原来的组件将会被复用,而不是重新创建

这意味着什么?这意味着组件的生命周期钩子不会再被调用

如果希望路由参数变化时组件能够作出响应,有两个办法:

  1. 使用 watch 属性监测 $route 对象
const User = {
    template: `
        <div>
            <p>The user name is {{ $route.params.name }}</p>
        </div>
    `,
    watch: {
        '$route': function (to, from) {
            console.log('changed')
        }
    }
}
  1. 使用 beforeRouteUpdate 导航护卫
const User = {
    template: `
        <div>
            <p>The user name is {{ $route.params.name }}</p>
        </div>
    `,
    beforeRouteUpdate (to, from, next) {
        console.log('changed')
    }
}

5、命名路由

在上面的例子中,我们使用 path 标识一个路由,事实上,我们还可以使用 name 为路由设置名称

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello</h1>
        <!-- 在链接到一个命名路由时,需要给 <router-link> 元素的 to 属性动态绑定一个对象 -->
        <router-link :to="{ name: 'user', params: { name: 'Alice'} }">To Alice User Page</router-link>
    </div>

    <script>
        const User = {
            template: '<p>The user name is {{ $route.params.name }}</p>'
        }

        const routes = [
            {
                name: 'user', // 为路由设置名称
                path: '/user/:name',
                component: User
            }
        ]

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

</html>

6、命名视图

与上面类似,我们可以使用 name<router-view> 设置名称,这允许我们在一个路由中使用多个同级的视图

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello</h1>
        <router-link to="/home">To Home Page</router-link>
        <router-view name="header"></router-view> <!-- 为视图设置名称 -->
        <router-view></router-view> <!-- 没有命名,默认为 default -->
        <router-view name="footer"></router-view>
    </div>

    <script>
        const Header = { template: '<h3>This is header</h3>' }
        const Container = { template: '<span>This is container</span>' }
        const Footer = { template: '<p>This is footer</p>' }

        const routes = [
            {
                path: '/home',
                // 使用 components 选项,不是 component
                components: { // 对象,键为视图名称,值为组件名称
                    default: Container,
                    header: Header,
                    footer: Footer
                }
            }
        ]

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

</html>

7、嵌套路由

在实际应用中,除了会有使用多个同级视图的情况,还有使用嵌套视图的情况,这时候我们有嵌套路由与之匹配

<!DOCTYPE html>
<html>

<head>
    <title>Demo</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <h1>Hello</h1>
        <router-link to="/home">To Home Page</router-link>
        <router-link to="/home/intro">To Intro Page</router-link>
        <router-link to="/home/info">To Info Page</router-link>
        <router-view></router-view>
    </div>

    <script>
        const Home = {
            // 在组件中也可以包含 <router-view>
            template: `
                <div>
                    <p>This is home page</p>
                    <router-view></router-view>
                </div>
            `
        }
        const Info = { template: '<p>This is info page</p>' }
        const Intro = { template: '<p>This is intro page</p>' }

        const routes = [
            {
                path: '/home',
                component: Home,
                // 使用 children 选项,相当于在子组件中配置 routes
                children: [
                    {
                        path: 'intro', // 相当于 /home/intro
                        component: Intro // 渲染在 Home 的 <router-view> 中
                    },
                    {
                        path: 'info', // 相当于 /home/info
                        component: Info // 渲染在 Home 的 <router-view> 中
                    }
                ]
            }
        ]

        const router = new VueRouter({
            routes
        })

        const app = new Vue({
            router
        }).$mount('#app')
    </script>
</body>

</html>

8、组件传参

还记得在动态路由那一小节的例子吗?我们使用 $route.params 获取 URL 参数

const User = {
    template: '<p>The user name is {{ $route.params.name }}</p>'
}

const routes = [
    {
        path: '/user/:name',
        component: User
    }
]

这样的写法,使得组件与对应的路由高度耦合,所以我们可以使用 props 进行解耦

const User = {
    props: ['name'], // 使用 props 属性
    template: '<p>The user name is {{ name }}</p>'
}

const routes = [
    {
        path: '/user/:name',
        component: User,
        props: true // 使用 props 属性,除了使用布尔值,还可以使用对象和函数
    }
]

9、编程式导航

在上面的例子中我们多次使用 <router-link> 进行导航,实际上我们还可以使用 router.push()

该方法有三个参数,分别是 location、onComplete 和 onAbort,它们的含义如下:

  • location:指定目标 URL,可以是字符串或对象
  • onComplete:导航成功后的回调函数
  • onAbort:导航终止后的回调函数

router.replace()router.push() 十分类似

不同之处在于 push 会向 history 栈中添加新的记录,而 replace() 将会直接替换当前的 history 记录

【 阅读更多 Vue 系列文章,请看 Vue学习笔记

版权声明:本博客属于个人维护博客,未经博主允许不得转载其中文章。
原文地址:https://www.cnblogs.com/wsmrzx/p/11245596.html