vue 基礎入門筆記 17:路由傳參的兩種方式

September發表於2019-08-19
  1. query
  2. params
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id="app">
        <!-- 1. 使用query方式傳參 -->
        <router-link to="/login?id=10&name=zs">登入</router-link>
        <!-- 2. 使用params方式傳參 -->
        <router-link to="/register/12/abc">註冊2</router-link>
        <router-view></router-view>
    </div>
    <script>
        let login = {
            template: '<h1>login---{{$route.query.name}}---{{$route.query.id}}</h1>',
            created() {
                //  query方式傳參
                console.log(this.$route)
                console.log(this.$route.query.id)
                console.log(this.$route.query.name)

            },
        }
        let register = { 
            template: '<h1>register</h1>',
            created(){
                //使用params方式傳參
                console.log(this.$route)
                console.log(this.$route.params.id)
                console.log(this.$route.params.name)
            }
        }
        const router = new VueRouter({
            routes: [
                { path: '/login', component: login },
                { path: '/register/:id/:name', component: register }]
        })
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            router
        });
        Vue.config.devtools = true
    </script>
</body>

</html>
本作品採用《CC 協議》,轉載必須註明作者和本文連結
日照香爐生紫煙

相關文章