Vue学习笔记(十) Vue Router

一、简介

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

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

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

二、安装

(1)经过 CDN 引用java

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

(2)经过 NPM 安装与使用vue-router

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

在项目中须要经过 Vue.use() 明确安装路由功能shell

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

Vue.use(VueRouter)

三、入门

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

首先建立一个命名为 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>
        // 一、定义组件
        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>
            `
        }

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

        // 三、建立 router 实例,传入 routes 配置
        const router = new VueRouter({
            routes // 缩写,至关于 routes : routes
        })

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

</html>

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

若是咱们点击 Home,URL 跳转为 index.html#/home(此时,匹配路由 /home,显示组件 Home)模块化

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

四、动态路由

下面考虑这样一个需求,咱们要为路由 /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')
    }
}

五、命名路由

在上面的例子中,咱们使用 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>

六、命名视图

与上面相似,咱们可使用 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>

七、嵌套路由

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

<!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>

八、组件传参

还记得在动态路由那一小节的例子吗?咱们使用 $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 属性,除了使用布尔值,还可使用对象和函数
    }
]

九、编程式导航

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

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

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

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

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

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

相关文章
相关标签/搜索