397 vue路由对象 - $route


  • 一个路由对象 (route object) :表示当前激活的路由的状态信息,包含了当前 URL 解析得到的信息

  • 一个哈希值路径 ==> 一个路由对象

  • $route.path

    • 类型: string
    • 字符串,对应当前路由的路径,总是解析为绝对路径,如 "/foo/bar"
    • # 后面、?前面的内容
  • $route.params

    • 类型: Object
    • 一个 key/value 对象,包含了动态片段和全匹配片段,如果没有路由参数,就是一个空对象。
  • $route.query

    • 类型: Object
    • 参数对象
    • 一个 key/value 对象,表示 URL 查询参数。例如,对于路径 /foo?user=1,则有 $route.query.user == 1,如果没有查询参数,则是个空对象。
  • $route.hash

    • 类型: string

      当前路由的 hash 值 (带 #) ,如果没有 hash 值,则为空字符串。

  • $route.fullPath

    • 类型: string
    • 全路径
    • 完成解析后的 URL,包含查询参数和 hash 的完整路径。
# 演示 : 
<router-link to="/detail/4?age=21#one">detail</router-link>
{ path: '/detail/:id?', component: detail } 
在组件内 created打印 this.$route
> fullPath: "/detail/4?id=001#one"
> hash : "#one"
> params : {id:'4'}
> query : {age : 21}
> path : '/detail/4'

06-$route.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <title>Document</title>
</head>

<body>
    <!-- 
       $route 路由对象 解析的url信息  哈希值的url信息
       - 哈希值 (#/one/4?age=30#aaa) ==> $route 
     -->
    <div id="app">
        <!-- 1. 入口 -->
        <!-- <router-link to="/one/4?age=30#aaa">one</router-link> -->
        <router-link to="/one/1">第一个</router-link>
        <router-link to="/one/2">第二个</router-link>

        <!-- 4. 出口 -->
        <router-view></router-view>
    </div>

    <script src="./vue.js"></script>
    <script src="./node_modules/vue-router/dist/vue-router.js"></script>
    <script>
        // 3. 组件
        const One = {
            template: `<div>one组件 {{ $route.params.id }}</div>`,
            created() {
                // 页面过程中的第一次的值,不会变化,因为created只执行一次
                console.warn(this.$route.params.id)
            },
            // 很重要的思想(★)
            // 使用watch 监听 $route 路由对象 获取里面的信息 【url变了,$route跟着变。】
            watch: {
                $route(newVal) {
                    console.warn(newVal)
                    console.warn(newVal.params.id)
                }
            }
        }

        //  实例化
        const router = new VueRouter({
            // 2. 规则
            routes: [{
                path: '/one/:id',
                component: One
            }]
        })

        const vm = new Vue({
            router,
            el: '#app',
            data: {}
        })
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/jianjie/p/12539491.html