Vue基本用法:vue-router路由、refs屬性和axios基本使用


Vue全家桶:vue + vue-router + vuex

vue + vue-router 主要用來做 SPA (single page application),單頁面應用

為什么要做單頁面應用?

傳統的路由跳轉,如果后端資源過多,會導致頁面出現“白屏現象”。讓前端來做路由,在某個生命周期的鈎子函數中發送 ajax ,然后數據驅動。即 為了用戶體驗。

vue-router 是vue的核心插件

vue-router 的使用:

// 1、創建匹配路由組件;
// 2、配置路由信息
// 3、在 router-link 中使用

示例代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    
</body>
<script src="./vue.js"></script>

<!-- 引入 vue-router -->
<script src="./vue-router.js"></script>
<script>
    /* 
    // 如果是模塊化編程, 下面的 Vue 和 VueRouter都是局部的,且下面的代碼等價於偽代碼: Vue.prototype.$VueRouter = VueRouter ,即 在Vue 的原型上掛載了 vue-router.js 提供的屬性 VueRouter
    Vue.use(VueRouter)
    */

    // 先定義兩個組件,這兩個組件要被用於路由中
    const Home = {
        data(){
            return {

            }
        },
        template:`<div>我是首頁</div>`,
    }

    const Course = {
        data(){
            return {

            }
        },
        template:`<div>我是課程組件</div>`,
    }

    // 創建路由
    const router = new VueRouter({
        // 定義路由規則;routes 對應的是一個列表,列表中是一個個對象;path 對應路由的路徑, component 對應路由的組件
        routes: [
            {
                path:'/',
                redirect:'/home'    // 重定向
            },

            {
                path: '/home',
                component: Home
            },

            {
                path: '/course',
                component: Course
            }
        ]
    })

    let App = {
        data(){
            return {

            }
        }, 

        /* 
        router-link 和 router-view 是 vue-router 提供的兩個全局組件;
        router-link 會被渲染成一個 a標簽,router-link 有一個屬性 to 相當於a標簽的 href 屬性, to 中的值要和 路由path 中的值一致;
        router-view 是路由組件的出口,即 path 對應的組件會渲染到 <router-view> 中
        */ 

        template:`
            <div>
                <div class='header'>
                    <router-link to="/home">首頁</router-link>
                    <router-link to="/course">課程</router-link>
                </div>

                <router-view></router-view>
            </div>
        `,
    }

    new Vue({
        el: '#app',

        // 掛載路由,即相當於  router:router
        router,     

        data(){
            return {

            }
        },

        template:`<App />`,
        components:{
            App
        }
    })

</script>

</html>

瀏覽器效果示例:

 

參考文檔: https://router.vuejs.org/zh/guide/#javascript

 

命名路由

命名路由可以動態綁定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

    </div>
    
</body>
<script src="./vue.js"></script>

<!-- 引入 vue-router -->
<script src="./vue-router.js"></script>
<script>
    
    // 先定義兩個組件,這兩個組件要被用於路由中
    const Home = {
        data(){
            return {

            }
        },
        template:`<div>我是首頁</div>`,
    }

    const Course = {
        data(){
            return {

            }
        },
        template:`<div>我是課程組件</div>`,
    }

    // 創建路由
    const router = new VueRouter({
        routes: [
            {
                path:'/',
                redirect:'/home'    // 重定向
            },

            // 命名路由
            {
                path: '/home',
                name: 'home-comp',  // 給路由起個名字
                component: Home
            },

            {
                path: '/course',
                name: 'course-comp',
                component: Course
            }
        ]
    })

    let App = {
        data(){
            return {

            }
        }, 

        // 動態綁定命名路由:<router-link> 中 :to 對應的是一個對象
        template:`
            <div>
                <div class='header'>
                    <router-link :to="{'name':'home-comp'}">首頁</router-link>
                    <router-link :to="{'name':'course-comp'}">課程</router-link>
                </div>

                <router-view></router-view>
            </div>
        `,
    }

    new Vue({
        el: '#app',

        // 掛載路由,即相當於  router:router
        router,     

        data(){
            return {

            }
        },

        template:`<App />`,
        components:{
            App
        }
    })

</script>

</html>

命名路由官方文檔:

https://router.vuejs.org/zh/guide/essentials/named-routes.html 

 

動態路由匹配

動態路由匹配規則 主要用於以下的 路由范式:
http:127.0.0.1:8080/user/{uid} 

示例代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

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

<script>
    /*
    動態路由匹配規則 主要用於以下的 路由范式:
    http:127.0.0.1:8080/user/{uid} 
    */

    const User = {
        data(){
            return {
                user_id:''
            }
        },

        template:`<div>我是用戶{{ user_id }}</div>`,

        created(){
            console.log(this.$route);   // $route 是路由信息對象;$route 是掛載到vue實例對象上的,能用 this.$route 獲取是因為通過 繼承。

            // 如果想拿地址欄上的某些參數,就去找 $route

            // 提醒一下,當使用路由參數時,例如從 /user/foo 導航到 /user/bar,原來的組件實例會被復用。因為兩個路由都渲染同個組件,比起銷毀再創建,復用則顯得更加高效。不過,這也意味着組件的生命周期鈎子不會再被調用。
        },

// 動態路由匹配 watch:{ $route(to, from) {
// 監視路由信息對象發生改變 console.log('to:', to); console.log('from:', from); console.log('uid:', to.params.uid); // 獲取到 uid 后就可以往后端發送 ajax this.user_id = to.params.uid } } } const router = new VueRouter({ routes:[ { path: '/user/:uid', // :uid 綁定動態傳入的數字值 name: 'user-comp', component: User } ] }) let App = { data(){ return { } }, // params 這個對象中的 key uid 即是 路由path 中的 :uid // 該 router-link 對應的模板樣式是 User 組件 template:` <div> <div class='header'> <router-link :to="{'name':'user-comp', params:{uid: 1}}">用戶1</router-link> <router-link :to="{'name':'user-comp', params:{uid: 2}}">用戶2</router-link> </div> <router-view></router-view> </div> `, } new Vue({ el: '#app', router, data(){ return { } }, template:`<App />`, components:{ App } }) </script> </html>

瀏覽器效果示例:

 

注: 就如 $route, 帶 $ 的屬性都是掛載到 vue 實例對象是的

 

編程式導航

$router:路由對象,即 VueRouter對象;一般用它來做編程式導航

編程式導航 vs 聲明式導航

聲明式導航示例:

<router-link :to="{'name':'user-comp', params:{uid: 1}}">用戶1</router-link>
<router-link :to="{'name':'user-comp', params:{uid: 2}}">用戶2</router-link>

編程式導航示例代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">

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

<script>

    const Home = {
        data(){
            return {

            }
        },
        template:`<div>我是首頁</div>`,
    }

    const User = {
        data(){
            return {
                user_id:null
            }
        },

        template:`
        <div>
            <p>我是用戶{{ user_id }}</p>
            <button @click='clickHandler'>跳轉</button>
        </div>
        `,

        methods:{

            // 編程式導航
            clickHandler(){
                // push 是 $router (路由對象)的一個方法,參數是一個包含命名路由的對象
                this.$router.push({
                    name: 'home-comp'
                })
            }
        },

        created(){
            console.log(this.$route);
        },

        watch:{
            $route(to, from) {
                this.user_id = to.params.uid
            }
        }
    }

    const router = new VueRouter({
        routes:[
            {
                path: '/user/:uid', 
                name: 'user-comp',
                component: User
            },
        ]
    })

    let App = {
        data(){
            return {

            }
        },

        template:`
            <div>
                <div class='header'>
                    <router-link :to="{'name':'user-comp', params:{uid: 1}}">用戶1</router-link>
                    <router-link :to="{'name':'user-comp', params:{uid: 2}}">用戶2</router-link>
                </div>

                <router-view></router-view>
            </div>
        `,
    }

    new Vue({
        el: '#app',
        router,
        data(){
            return {

            }
        },
        template:`<App />`,
        components:{
            App
        }
    })
</script>
</html>

瀏覽器效果示例:

編程式導航文檔:

https://router.vuejs.org/zh/guide/essentials/navigation.html 

 

Vue 獲取原生DOM的方式

Vue提供的獲取原生DOM 的方式,是給標簽或組件添加 refs 屬性:
通過 this.$refs 來獲取,如

<div ref='neo'></div>

如果在當前組件中想獲取上述 div 標簽這個DOM元素,可通過  this.$refs.neo 獲取到上述 div 對象

如果是給 html 標簽添加 ref ,那么 this.$refs.neo 獲取到的是原始的DOM元素;
如果是給 Vue 組件添加 ref ,那么通過 this.$refs.neo 獲取到的是 組件實例化對象 

代碼示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        
    </div>

<script src="./vue.js"></script>
<script>
    // 想要實現的效果: DOM加載完成后,自動獲取 input 輸入框的焦點

    Vue.component('Test', {
        data(){
            return {

            }
        },
        template:`
            <div>我是測試組件</div>
        `,
    })

    let App = {
        data(){
            return {

            }
        },

        template:`
            <div>
                <input type="text" ref='inputss'>
                <Test ref='test-compnt' />
            </div>
        `,

        mounted(){
            console.log(this.$refs.inputss);    // 獲取原始的 input 這個DOM元素; <input type="text">
            this.$refs.inputss.focus();     // 自動獲取input 輸入框的焦點

            // this.$refs 是一個對象
            console.log(this.$refs);    // {inputss: input, test-compnt: VueComponent}

            for(let key in this.$refs){
                console.log('keys:', key, 'val:', this.$refs[key] );
            }
        }
    }

    new Vue({
        el: '#app',
        data(){
            return {

            }
        },

        template:`<App />`,

        components:{
            App
        }
    })
</script>
</body>
</html>

瀏覽器效果示例:

 

axios 的基本使用:

1、在項目中下載 axios 組件

npm i axios -S

2、在項目中引入 axios

// main.js 中全局引入 axios

// 引入 axios
import Axios from 'axios'

// 把 axios 掛載到 vue的原型上
Vue.prototype.$https = Axios    // $https 這個名字可以自己起

// 設置公共的url;以后在利用 axios 給某個鏈接(如 users/edit)發送請求時, 鏈接會自動和這個 baseURL 拼接到一起
Axios.defaults.baseURL = 'https://api.example.com';

3、 在組件中使用 axios

// 為給定 ID 的 user 創建GET請求
this.$https.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

 

官方文檔:

http://www.axios-js.com/zh-cn/docs/index.html

 


免責聲明!

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



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