玩轉(zhuǎn)Vue_路由vue-router

什么是路由

  1. 對于普通的網(wǎng)站,所有的超鏈接都是URL地址,所有的URL地址都對應(yīng)服務(wù)器上對應(yīng)的資源;
  2. 對于單頁面應(yīng)用程序來說,主要通過URL中的hash(#號)來實現(xiàn)不同頁面之間的切換,同時,hash有一個特點:HTTP請求中不會包含hash相關(guān)的內(nèi)容;所以,單頁面程序中的頁面跳轉(zhuǎn)主要用hash實現(xiàn);
  3. 在單頁面應(yīng)用程序中,這種通過hash改變來切換頁面的方式,稱作前端路由(區(qū)別于后端路由);

在 vue 中使用 vue-router

1.導(dǎo)入 vue-router 組件類庫:

<!-- 1. 導(dǎo)入 vue-router 組件類庫 -->
<script src="./vue-router-2.7.0.js"></script>

2.使用 router-link 組件來導(dǎo)航

<!-- 2. 使用 router-link 組件來導(dǎo)航 -->
<router-link to="/login">登錄</router-link>
<router-link to="/register">注冊</router-link>

3.使用 router-view 組件來顯示匹配到的組件

<!-- 3. 使用 router-view 組件來顯示匹配到的組件 -->
<router-view></router-view>

4.注冊組件

// 4.1 使用 Vue.extend 來創(chuàng)建登錄組件
const login = {
     template: '<h1>登錄組件</h1>'
}

// 4.2 使用 Vue.extend 來創(chuàng)建注冊組件
const register = {
     template: '<h1>注冊組件</h1>'
}

5.指定路由規(guī)則

var router = new VueRouter({
        routes: [
            { path: '/login', component : login },
            { path: '/register', component : register }
        ]
});

6.啟用路由規(guī)則

// 創(chuàng)建 Vue 實例,得到 ViewModel
var vm = new Vue({
        el: '#app',
        data: {},
        methods: {},
        router // 啟用路由,相當(dāng)于router : router
});

路由攜帶參數(shù)

<!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>目標(biāo):主要練習(xí)父子組件之間傳值</title>
</head>

<body>
    <div id="app">
        <router-link to="/login/1">登錄</router-link>
        <router-link to="/register/2">注冊</router-link>

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

    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        // 4.1 使用 Vue.extend 來創(chuàng)建登錄組件
        const login = {
            template: '<h1>登錄組件----{{this.$route.params.id}}</h1>'
        }

        // 4.2 使用 Vue.extend 來創(chuàng)建注冊組件
        const register = {
            template: '<h1>注冊組件----{{this.$route.params.id}}</h1>'
        }

        var router = new VueRouter({
            routes: [
                { path: '/login/:id', component : login },
                { path: '/register/:id', component : register }
            ]
        });

        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            router
        });
    </script>
</body>

</html>

路由的嵌套

<!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>路由嵌套</title>
</head>

<body>
    <div id="app">
        <router-link to="/account">Account</router-link>
        <router-view></router-view>
    </div>

    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        const account = {
            template : `<div>
                    這是account組件
                    <router-link to="/account/login">登錄</router-link> 
                    <router-link to="/account/register">注冊</router-link> 
                    <router-view></router-view>
            </div>`
        }
        const login = {
            template: '<h1>登錄組件</h1>'
        }
        const register = {
            template: '<h1>注冊組件</h1>'
        }
        const router = new VueRouter({
            routes: [
                {
                    path : '/account',redirect : '/account/login'
                },
                {
                    path : '/account',
                    component : account,
                    children : [
                        {
                            path:'login',
                            component : login 
                        },
                        {
                            path : 'register',
                            component : register 
                        }
                    ]
                }
            ]
        })
        // Vue 實例
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            router,
            components : {
                account
            }
        });
    </script>
</body>

</html>

命名視圖實現(xiàn)經(jīng)典布局

<!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>命名視圖實現(xiàn)經(jīng)典布局</title>
    <style>
        .header {
            border: 1px solid red;
        }

        .content {
            display: flex;
        }

        .sidebar {
            flex: 2;
            border: 1px solid green;
            height: 500px;
        }

        .mainbox {
            flex: 8;
            border: 1px solid blue;
            height: 500px;
        }
    </style>
</head>

<body>
    <div id="app">
        <router-view></router-view>
        <div class="content">
            <router-view name="a"></router-view>
            <router-view name="b"></router-view>
        </div>
    </div>

    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        var header = Vue.component('header', {
            template: '<div class="header">header</div>'
        });

        var sidebar = Vue.component('sidebar', {
            template: '<div class="sidebar">sidebar</div>'
        });

        var mainbox = Vue.component('mainbox', {
            template: '<div class="mainbox">mainbox</div>'
        });

        // 創(chuàng)建路由對象
        var router = new VueRouter({
            routes: [{
                path: '/',
                components: {
                    default: header,
                    a: sidebar,
                    b: mainbox
                }
            }]
        });

        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            router
        });
    </script>
</body>

</html>

watch屬性的使用

考慮一個問題:想要實現(xiàn) 名 和 姓 兩個文本框的內(nèi)容改變,則全名的文本框中的值也跟著改變;(用以前的知識如何實現(xiàn)???)

監(jiān)聽data中屬性的改變:
<!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>watch</title>
</head>

<body>
    <div id="app">
        <input type="text" v-model="firstName"> +
        <input type="text" v-model="lastName"> =
        <span>{{fullName}}</span>
    </div>

    <script src="./js/vue.js"></script>
    <script src="./js/vue-router.js"></script>
    <script>
        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {
                firstName: 'jack',
                lastName: 'chen',
                fullName: 'jack - chen'
            },
            methods: {},
            watch: { // watch監(jiān)聽數(shù)據(jù)的改變
                'firstName': function (newVal, oldVal) { // 第一個參數(shù)是新數(shù)據(jù),第二個參數(shù)是舊數(shù)據(jù)
                    this.fullName = newVal + ' - ' + this.lastName;
                },
                'lastName': function (newVal, oldVal) {
                    this.fullName = this.firstName + ' - ' + newVal;
                }
            }
        });
    </script>
</body>

</html>
監(jiān)聽對象的改變
<!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>watch</title>
</head>

<body>

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

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

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

    <script>
        var login = {
            template: '<h1>登錄組件</h1>'
        };

        var register = {
            template: '<h1>注冊組件</h1>'
        };

        var router = new VueRouter({
            routes: [
                {
                    path: "/login",
                    component: login
                },
                {
                    path: "/register",
                    component: register
                }
            ]
        });

        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {},
            router: router,
            watch: {
                '$route': function (newVal, oldVal) {
                    if (newVal.path === '/login') {
                        console.log('這是登錄組件');
                    }
                }
            }
        });
    </script>
</body>

</html>

computed計算屬性的使用

<!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>watch</title>
</head>

<body>

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

    <div id="app">
        <input type="text" v-model="firstName"> +
        <input type="text" v-model="lastName"> =
        <span>{{fullName}}</span>
    </div>

    <script>
        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {
                firstName: 'jack',
                lastName: 'chen'
            },
            methods: {},
            computed: { // 計算屬性; 特點:當(dāng)計算屬性中所以來的任何一個 data 屬性改變之后,都會重新觸發(fā) 本計算屬性 的重新計算,從而更新 fullName 的值
                fullName() { // 相當(dāng)于get方法,得到的是fullName屬性
                    return this.firstName + ' - ' + this.lastName;
                }
            }
        });
    </script>
</body>

</html>
有setter和getter的計算屬性
<!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>watch</title>
</head>

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

    <div id="app">
        <input type="text" v-model="firstName">
        <input type="text" v-model="lastName">
        <!-- 點擊按鈕重新為 計算屬性 fullName 賦值 -->
        <input type="button" value="修改fullName" @click="changeName">

        <span>{{fullName}}</span>
    </div>

    <script>
        // 創(chuàng)建 Vue 實例,得到 ViewModel
        var vm = new Vue({
            el: '#app',
            data: {
                firstName: 'jack',
                lastName: 'chen'
            },
            methods: {
                changeName() {
                    this.fullName = 'TOM - chen2';
                }
            },
            computed: {
                fullName: {
                    get: function () {
                        return this.firstName + ' - ' + this.lastName;
                    },
                    set: function (newVal) {
                        var parts = newVal.split(' - ');
                        this.firstName = parts[0];
                        this.lastName = parts[1];
                    }
                }
            }
        });
    </script>
</body>

</html>

watch、computed和methods之間的對比

  1. computed屬性的結(jié)果會被緩存,除非依賴的響應(yīng)式屬性變化才會重新計算。主要當(dāng)作屬性來使用;
  2. methods方法表示一個具體的操作,主要書寫業(yè)務(wù)邏輯;
  3. watch一個對象,鍵是需要觀察的表達(dá)式,值是對應(yīng)回調(diào)函數(shù)。主要用來監(jiān)聽某些特定數(shù)據(jù)的變化,從而進(jìn)行某些具體的業(yè)務(wù)邏輯操作;可以看作是computed和methods的結(jié)合體;
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容