• vue-router的基本使用


    gitHub地址:https://github.com/huangpna/vue_learn/example里面的lesson14

    安装

    直接引入

    <script src="vue.js"></script>
    <script src="vue-router.js"></script>

    vue-router下载链接:点击复制代码

    NPM下载

    npm install vue-router

    如果在一个模块化工程中使用它,必须要通过 Vue.use() 明确地安装路由功能:
    在你的文件夹下的 src 文件夹下的 main.js 文件内写入以下代码

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter)

    入门

    先简单写一个例子:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index1</title>
    </head>
    <body>
        <div id="app">
            <h1>HELLO APP!</h1>
            <p>
                <router-link to="/foo">to foo</router-link>
                <router-link to="/bar">to bar</router-link>
            </p>
            <router-view></router-view>
        </div>
    </body>
    <script src="../js/vue.js"></script>
    <script src="../js/vue-router.js"></script>
    <script>
        const Foo = { template: '<div>foo</div>' }
        const Bar = { template: '<div>bar</div>' }
      //配置路由
    const routes = [ { path: '/foo', component: Foo }, { path: '/bar', component: Bar } ];
      //实现路由实例化
    const router = new VueRouter({ routes });
      //挂载到Vue的实例上
    const app = new Vue({ router }).$mount('#app'); </script> </html>

     <router-link> 默认会被渲染成一个 <a> 标签  >> to=" " 为我们定义的路由

    <router-view> 路由匹配到的组件将渲染在这里

    ------上述例子实现效果可拷贝代码在本地查看。

    动态路由匹配

    我们经常需要将具有给定模式的路线映射到同一个组件。例如,我们可能有一个User应该为所有用户呈现但具有不同用户ID的组件。vue-router我们可以在路径中使用动态段以实现:

    栗子:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index2</title>
    </head>
    <body>
    <div id="app2">
        <p>
            <router-link to="/user/1">to 用户一</router-link>
            <router-link to="/user/2">to 用户二</router-link>
        </p>
        <router-view></router-view>
    </div>
    </body>
    <script src="../js/vue.js"></script>
    <script src="../js/vue-router.js"></script>
    <script>
        const user = { template: '<div>{{$route.params.id}}</div>' };
        const routes = [
            { path: '/user/:id', component: user}
        ];
        const router = new VueRouter({
            routes
        });
        const app = new Vue({
            router
        }).$mount('#app2');
    </script>
    </html>

    动态段由冒号表示:匹配路径时,动态段的值将this.$route.params在每个组件中公开

    除此之外$route.params,该$route对象还公开了其他有用的信息,例如$route.query(如果URL中有查询)$route.hash等。您可以在API参考中查看完整的详细信息

    ------上述例子实现效果可拷贝代码在本地查看。

    嵌套路由

    我们经常将动态路由和嵌套路由共同使用,嵌套路由即是在原路由的基础上增加一个 children ,children 是一个数组.并且我们还需要在原来的组件上添加< router-view >来渲染 chlidren 里面的路由.

    栗子:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>index3</title>
        <style>
            #app3>p>a{
                padding:5px 10px;
            }
            .router-link-exact-active{
                background-color: darkslateblue;
                border-radius: 4%;
                color:#FFF;
            }
        </style>
    </head>
    <body>
        <div id="app3">
            <p>
                <router-link to="/user/foo">/user/foo</router-link>
                <router-link to="/user/foo/profile">/user/foo/profile</router-link>
                <router-link to="/user/foo/posts">/user/foo/posts</router-link>
            </p>
            <router-view></router-view>
        </div>
    </body>
    <script src="../js/vue.js"></script>
    <script src="../js/vue-router.js"></script>
    <script>
        const user = {
            template: `
            <div>
                <h1>User {{$route.params.id}}</h1>
                <router-view></router-view>
            </div>
            `
        };
        const userHome = { template: '<div>userHome</div>' };
        const userProfile = { template: '<div>userProfile</div>' };
        const userPosts = { template: '<div>userPosts</div>' };
        const routes = [
            {
                path: '/user/:id',
                component: user,
                children: [
                    {
                        path: '',      //通过上述配置,当您访问时/user/foo,内部User的任何内容都不会呈现,因为没有子路径匹配。也许你确实希望在那里渲染一些东西。在这种情况下,您可以提供一个空的子路径路径
                        component: userHome
                    },
                    {
                        path: 'profile',
                        component: userProfile
                    },
                    {
                        path: 'posts',
                        component: userPosts
                    }
                ]
            }
        ];
        const router = new VueRouter({
            routes
        });
        const app3 = new Vue({
            router
        }).$mount('#app3');
    </script>
    </html>

    ------上述例子实现效果可拷贝代码在本地查看。

    程序化导航

    除了使用<router-link>为声明性导航创建锚标签之外,我们可以使用路由器的实例方法以编程方式执行此操作。

    router.push(location)

    想要导航到不同的 URL,则使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

    当你点击 <router-link> 时,这个方法会在内部调用,所以说,点击 <router-link :to="..."> 等同于调用 router.push(...)。

    该方法的参数可以是一个字符串路径,或者一个描述地址的对象。例如:

    // 字符串
    router.push('home')
    
    // 对象
    router.push({ path: 'home' })
    
    // 命名的路由
    router.push({ name: 'user', params: { userId: 123 }})
    
    // 带查询参数,变成 /register?plan=private
    router.push({ path: 'register', query: { plan: 'private' }})

    下述router.replace跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 ——而是替换掉当前的 history 记录。

    router.replace(location)

    router.go这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)。

    // 在浏览器记录中前进一步,等同于 history.forward()
    router.go(1)
    
    // 后退一步记录,等同于 history.back()
    router.go(-1)
    
    // 前进 3 步记录
    router.go(3)
    
    // 如果 history 记录不够用,那就默默地失败呗
    router.go(-100)
    router.go(100)

    命名路由

    有时我们通过一个名称来标识一个路由显得更方便一些,特别是在链接一个路由,或者是执行一些跳转的时候。你可以在创建 Router 实例的时候,在 routes 配置中给某个路由设置名称。

    我们直接在路由下添加一个 name 即可.

    var routes = [
        {
            path:"/one",
            name:"one",
            component:{template:"#a"}
        },
        {
            path:"/two",
            name:"two",
            component:{template:"#b"},
        },
    ]

    要链接到一个命名路由,可以给 router-link 的 to 属性传一个对象:

    <router-link :to="{ name: 'one', params: { userId: 123 }}">User</router-link>
    <router-link :to="{ name: 'two'}">User</router-link>

    另外以编程的方式实现以上效果可使用router.push()

    router.push({ name: 'user', params: { userId: 123 }})

     路由传参获取:

    this.$route.params.userId

    命名视图

     有时您需要同时显示多个视图而不是嵌套它们,例如创建具有sidebar视图和main视图的布局这就是命名视图派上用场的地方。您可以拥有多个并为每个插座指定一个名称,而不是在您的视图中只有一个插座。router-view没有名字的default作为其名称。

    <router-view class="view one"></router-view>
    <router-view class="view two" name="a"></router-view>
    <router-view class="view three" name="b"></router-view>

    通过使用组件呈现视图,因此多个视图需要同一路径的多个组件。确保使用components(带有s)选项:

    const router = new VueRouter({
      routes: [
        {
          path: '/',
          components: {
            default: Foo,
            a: Bar,
            b: Baz
          }
        }
      ]
    })

    栗子:链接

    嵌套命名视图

    栗子:链接

    重定向和别名

    重定向:

    重定向也在routes配置中完成要重定向/a/b

    const router = new VueRouter({
      routes: [
        { path: '/a', redirect: '/b' }
      ]
    })

    栗子:链接

    重定向也可以定位到命名路线:

    const router = new VueRouter({
      routes: [
        { path: '/a', redirect: { name: 'foo' }}
      ]
    })

    栗子:链接

    别名

    /a的别名是/b,意味着,当用户访问/b时,URL会保持/b,但是路由匹配为/a,就像用户访问/a一样。

    对应的路由配置为:

    const router = new VueRouter({
         routes: [
             { path: '/a', component:A, alias: '/b' }
            ]
        })

    别名的功能让我们可以自由地将ui结构映射到任意的URL, 而不是受限于配置的嵌套路由结构。

  • 相关阅读:
    暑假周总结02
    音乐播放器
    setInterval、控制停止和继续
    暑假周总结01
    ul li、a标签的下划线
    innerHTML、document获取对象、className修改样式
    领扣(LeetCode)N叉树的层序遍历 个人题解
    领扣(LeetCode)两句话中的不常见单词 个人题解
    领扣(LeetCode)二叉树的中序遍历 个人题解
    领扣(LeetCode)用队列实现栈 个人题解
  • 原文地址:https://www.cnblogs.com/1156063074hp/p/10233814.html
Copyright © 2020-2023  润新知