zoukankan      html  css  js  c++  java
  • 非node环境 vue-rouder 学习笔录2 路由监听和动态路由匹配

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

    实例一、在路由中设置一个参数

    html部分
    <div id="app">
    <p>
    <router-link to="/user/foo">/user/foo</router-link>
    <router-link to="/user/bar">/user/bar</router-link>
    </p>
    <router-view></router-view>
    </div>

    js部分

    <script>
    const User = {
    template: '<div>User {{ $route.params.id }}</div>',
    watch: {'$route' (to, from) {
    //监听路由
    console.log(to);
    console.log(from);
    }
    }
    }

    实例二 在路由中设置多个路径参数

    const router= new VueRouter({
    routes:[{path:'/user/:id',component:User}]
    })
    new Vue({
    router
    }).$mount("#app")
    </script>

    <div id="app">
    <p>
    <router-link to="/user/evan/post/123">/user/foo</router-link>
    <router-link to="/user/evan/post/456">/user/bar</router-link>
    </p>
    <router-view></router-view>
    </div>
    <script>
    const User = {
    template: '<div>User {{ $route.params.post_id }} {{ $route.params.username }}</div>',
    watch: {'$route' (to, from) {
    console.log(to);
    console.log(from);
    }
    }
    }
    const router= new VueRouter({
    routes:[{path:'/user/:username/post/:post_id',component:User}]
    })
    new Vue({
    router
    }).$mount("#app")
    </script>

    高级匹配中可以进行正则的匹配

    routes: [
    { path: '/' },
    // params are denoted with a colon ":"
    { path: '/params/:foo/:bar' },
    // a param can be made optional by adding "?"
    { path: '/optional-params/:foo?' },
    // a param can be followed by a regex pattern in parens
    // this route will only be matched if :id is all numbers
    { path: '/params-with-regex/:id(\d+)' },
    // asterisk can match anything
    { path: '/asterisk/*' },
    // make part of th path optional by wrapping with parens and add "?"
    { path: '/optional-group/(foo/)?bar' }
    ]

    除了 $route.params 外,$route 对象还提供了其它有用的信息,例如,$route.query(如果 URL 中有查询参数)、$route.hash 等等。你可以查看 API 文档 的详细说明。

  • 相关阅读:
    java匿名对象
    Java面向对象详解
    Java语言基本语法
    Win7下JDK环境变量的设置
    LeetCode-Shortest Word Distance
    LeetCode-Count Complete Tree Nodes
    LeetCode-Palindrome Pairs
    LeetCode- Implement Trie (Prefix Tree)
    LeetCode-Lowest Common Ancestor of a Binary Tre
    LeetCode- Binary Tree Longest Consecutive Sequence
  • 原文地址:https://www.cnblogs.com/itadong/p/7110887.html
Copyright © 2011-2022 走看看