399 vue命名路由 ==> :to="{ name : 'xxx' }"

  • 有时候,通过一个名称来标识一个路由显得更方便一些,
  • 特别是在链接一个路由,或者是执行一些跳转的时候。 ===> 场景
  • 你可以在创建 Router 实例的时候,在 routes 配置中给某个路由设置名称。 ==> 如何命名
# 命名
routes: [
    {
        path: '/parent',
        name: 'parent',
        component: parent
    }
]

# 入口链接 + 跳转  (使用 path 和 name 的转换)
<!-- 方式1 : url手动写 -->

<!-- 方式2 : 入口链接 声明式导航 -->
<router-link to="/parent">点击</router-link>
<router-link :to="{ name : 'parent' }">点击</router-link>  # 忘了 带 : 原始对象类型

<!-- 方式3 : 编程式导航 -->
 fn() {
     // this.$router.push('/parent')
     this.$router.push({
         name: 'parent'
     })
 }

09-命名路由.html

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

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

<body>
    <div id="app">
        <!-- 1. 入口 -->
        <!-- 下面两个用的都是 path -->
        <!-- 
            <router-link to="/one">one</router-link>
            <router-link to="/two">two</router-link> 
        -->
        <!-- to前面不加冒号,就会把属性值当做字符串 -->
        <router-link :to="{ name : 'one' }">one</router-link>
        <router-link :to="{ name :'two' }">two</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组件</div>`
        }
        const Two = {
            template: `<div>two组件</div>`,
            created() {
                console.log(this.$route.name)
            }
        }

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

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

</html>

原文地址:https://www.cnblogs.com/jianjie/p/12539676.html