VUE 在組件中 獲取 路由信息


原文:
https://www.cnblogs.com/robinunix/p/11045870.html
https://www.cnblogs.com/miluluyo/p/11190648.html

一、核心代碼

1、獲取參數

this.$route.query.id
this.$route.query

2、頁面跳轉

<router-link to="/login?id=123">登錄</router-link>

3、方法跳轉

this.$router.push({ path: '/login', query: { id: '456' } });

二、全部代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <!--<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>-->


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


    <div id="components-demo">
        <component-a></component-a>

        <router-link to="/login?id=123">登錄</router-link>
        <router-link to="/register">注冊</router-link>

        <button v-on:click="fn1">測試點擊調整頁面</button>

        <router-view></router-view>
    </div>


    <script type="text/javascript">

        // 組件的局部注冊
        var ComponentA = {
            data: function () {// 組件的數據
                return {
                    count: 0
                }
            },
            template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'// 組件的模板
        };
        var Component_login = {
            template: '<h2>登錄----{{$route.query.id}}------{{id}}-----{{name}}</h2>',
            data: function () {
                return {
                    name: 'name1',
                    //id: this.$route.query.id// 獲取url參數,這個不可以用,不是實時的!!!
                };
            },
            computed: {
                id: function () {
                    return this.$route.query.id// 計算屬性的 獲取url參數,這個可以用
                }
            },
            created() {
                console.log(this.$route.query)
            },
        };
        var Component_register = { template: '<h1>Component2</h1>' };


        // 路由
        var routerObj = new VueRouter({
            routes: [
                { name:'login', path: '/login', component: Component_login },
                { name:'register', path: '/register', component: Component_register }
            ]
        })


        new Vue({
            el: '#components-demo',
            components: {
                'component-a': ComponentA,
                'component-1': Component_login,
                'component-2': Component_register
            },
            router: routerObj,
            methods: {
                fn1: function () {// 跳轉頁面
                    //this.$router.push({ name: 'login', query: { id: '456' } });
                    this.$router.push({ path: '/login', query: { id: '456' } });
                }
            }
        })

    </script>


</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM