千锋 Vue 详细笔记整理4

简介: 千锋 Vue 详细笔记整理

11.3.1 GET 格式的请求

  • axios.get(url).then(function);
  • 使用 response.data 读取 JSON 数据:
axios
    .get('json/json_demo.json')
    .then(response => (this.info = response.data.sites))
    .catch(function (error) {
    console.log(error)
})

axios.get(url,{}).then(function);

  • GET 方法传递参数格式 (使用 axios 的 get 请求传递参数,需要将参数设置在 params 下)
// 直接在 URL 上添加参数 ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 也可以通过 params 设置参数:
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

11.3.2 POST 格式的请求

  • axios.post(url, {}).then(function);
  axios
      .post("https://localhost:9098/blog/upload", {
      name: "张三",
      age: "20"
  })
      .then(response => (this.info2 = response))
      .catch(function (error) {
      console.log(error)
  })

11.3.3 自定义请求

自定义请求:自定义请求方式、请求参数、请求头、请求体(post)

axios({
    url: "https://localhost:9098/blog/upload",
    method: "post",
    params: {
        // 设置请求行传值
        name: "张三",
        limit: 15
    },
    headers: {
        // 设置请求头
    },
    data: {
        // 设置请求体 (post / put)
    }
}).then(function (res) {
    console.log(res)
});

11.3.4 请求方法别名

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

当使用别名方法时,不需要在config中指定url,method和data属性。

11.4 并发请求

axios.all()、axios.spread() 两个辅助函数用于处理同时发送多个请求,可以实现在多个请求都完成后再执行一些逻辑。


处理并发请求的助手函数:


axios.all(iterable)

axios.spread(callback)

<div id="app-25">
    <button type="button" @click="test">测试</button>
</div>
<script type="text/javascript">
    var vm = new Vue({
        el: "#app-25",
        data: {
        },
        methods: {
            test: function () {
                // 发送异步请求
                axios
                    .all([f1(), f2()])
                    .then(axios.spread(function (res1, res2) {
                    // 两个请求都要执行完毕
                    console.log("所有请求都完成")
                    console.log(res1);
                    console.log(res2);
                }));
            }
        }
    });
    function f1() {
        console.log('调用第一个接口')
        return axios.get("json/json_demo.json");
    }
    function f2() {
        console.log('调用第二个接口')
        return axios.get("json/json_demo2.json");
    }
</script>

注:两个请求执行完成后,才执行 axios.spread() 中的函数,且 axios.spread() 回调函数的的返回值中的请求结果的顺序和请求的顺序一致

F12 查看控制台输出情况

11.5 箭头函数

11.5.1 axios 回调函数的参数 res

res 并不是接口返回的数据,而是表示一个响应数据:res.data 才表示接口响应的数据

11.5.2 箭头函数

<script type="text/javascript">
    var vm = new Vue({
        el: "#app-24",
        data: {
            songs: ""
        },
        methods: {
            test4: function () {
                // 发送异步请求
                axios
                    .get("json/json_demo2.json")
                    .then((res) => {
                    // res 并不是接口返回的数据,而是表示一个响应数据:res.data 才表示接口响应的数据
                    this.songs = res.data;
                    console.log(res.data)
                })
            }
        }
    })
</script>

十二、 路由 router

router 是由 vue 官方提供的用于实现组件跳转的插件。

Vue Router 是 Vue.js (opens new window)官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌。

12.1 路由插件的引用

12.1.1 离线

12.1.2 在线 CDN

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

当你要把 Vue Router 添加进来,我们需要做的是,将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        body {
            padding: 0px;
            margin: 0px;
        }
        ul {
            list-style: none;
        }
        ul li {
            display: inline;
            float: left;
            margin-left: 15px;
        }
    </style>
    <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="app-26">
        <div style="width: 100%; height: 70px; background: #00BFFF;">
            <table>
                <tr>
                    <td>
                        <img src="img/1.jpg" height="70" style="margin-left: 100px;" />
                    </td>
                    <td>
                        <ul>
                            <li>
                                <router-link to="/index">首页</router-link>
                            </li>
                            <li>
                                <router-link to="/java">Java</router-link>
                            </li>
                            <li>
                                <router-link to="/python">Python</router-link>
                            </li>
                            <li>
                                <router-link to="/vue">Vue</router-link>
                            </li>
                        </ul>
                    </td>
                </tr>
            </table>
        </div>
        <div style="width: 100%; height: 680px; background: salmon;">
            <router-view></router-view>
        </div>
    </div>
    <script type="text/javascript">
        <!-- vue 的路由旨在为单页面应用开发提供便携 -->
        // 定义链接跳转的模板(组件)
        const t1 = {
            template: `<p align="center">index</p>`
        };
        const t2 = {
            template: `<p align="center" >Java</p>`
        };
        const t3 = {
            template: `<p align="center">Python</p>`
        };
        const t4 = {
            template: `<p align="center">Vue</p>`
        };
        const my_router = new VueRouter({
           routes: [
               {
                   path: '/index',
                   component: t1
               },
               {
                   path: '/java',
                   component: t2
               },
               {
                   path: '/python',
                   component: t3
               },
               {
                   path: '/vue',
                   component: t4
               }
           ]
        });
        var vm = new Vue({
           el: '#app-26',
            router: my_router
        });
    </script>
</body>
</html>

点击链接,根据路由,跳转并显示对应的组件模板

12.2 动态路由匹配

12.2.1 通配符

* 可以匹配任意路径

例如:

  • /user-* 匹配所有以 user-开头的任意路径
  • /* 匹配所有路径
    const my_router = new VueRouter({
    routes: [
    {
    path: ‘/user-’,
    component: t4

  • },
    {
    path: '/
    ’,
    component: t5
    }
    ]
    });

注意:如果使用通配符定义路径,需要注意路由声明的顺序

12.2.2 路由参数

  • /index/:id 可以匹配/index/开头的路径
    首页

12.2.3 优先级

如果一个路径匹配了多个路由,则按照路由的配置顺序:路由定义的越早优先级就越高。

12.3 嵌套路由

在一级路由的组件中显示二级路由

<div id="app-28">
    <div style="width: 100%; height: 20px; background: #00BFFF;">
        <router-link to="/index">首页</router-link>
        <router-link to="/index/t2">首页-t2</router-link>
        <router-link to="/index/t3">首页-t3</router-link>
        <router-view></router-view>
    </div>
</div>
<script type="text/javascript">
    <!-- vue 的路由旨在为单页面应用开发提供便携 -->
    // 1. 定义链接跳转的模板(组件)
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    index
                    <hr />
                    <router-view></router-view>
    </div>`
    };
    const t2 = {
        template: `<div>t2</div>`
    };
    const t3 = {
        template: `<div>t3</div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/index',
                component: t1,
                children: [
                    {
                        path: "t2",
                        component: t2
                    },
                    {
                        path: "t3",
                        component: t3
                    }
                ]
            },
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-28',
        router: my_router
    });
</script>

12.4 编程式导航

12.4.1 push()

<div id="app-29">
    <div style="width: 100%; height: 20px; background: #00BFFF;">
        <!-- <router-link to="/index">首页</router-link> -->
        <button type="button" @click="test">首页按钮</button>
        <router-view></router-view>
    </div>
</div>
<script type="text/javascript">
    <!-- vue 的路由旨在为单页面应用开发提供便携 -->
    // 1. 定义链接跳转的模板(组件)
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    index
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/index',
                component: t1
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-29',
        router: my_router,
        methods: {
            test: function () {
                // js 代码实现路由跳转,编程式导航
                my_router.push("/index");
            }
        }
    });
</script>

12.4.2 push() 参数

// 1. 字符串
my_router.push("/index");
// 2. 对象
my_router.push({path: "/index"});
// 3. 命名的路由 name 参数指的是定义路由时指定的名字
my_router.push({name: "r1", params: {id: 101}});
// 4. URL 传值,相当于 /index?id=101
my_router.push({path: "/index", query: {id: 101}});

12.4.3 replace()

功能与 push() 一致,区别在于 replace() 不会向 history 添加新的浏览记录

12.4.4 go()

参数为一个整数,表示在浏览器历史记录中前进或后退多少步 相当于 windows.history.go(-1) 的作用

12.5 命名路由

命名路由:在定义路由的时候可以给路由指定 name,我们在进行路由导航时可以通过路由的名字导航

 <div id="app-30">
     <div style="width: 100%; height: 20px; background: #00BFFF;">
         <input type="text" v-model="rName" />
         <router-link :to="{name: rName}">t1</router-link>
         <button type="button" @click="test">首页按钮2</button>
         <router-view></router-view>
     </div>
</div>
<script type="text/javascript">
    <!-- vue 的路由旨在为单页面应用开发提供便携 -->
    // 1. 定义链接跳转的模板(组件)
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    t1
    </div>`
    };
    const t2 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    t2
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/index',
                name: "r1",
                component: t1
            },
            {
                path: '/index2',
                name: "r2",
                component: t2
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-30',
        data: {
            rName: "r1"
        },
        router: my_router,
        methods: {
            test: function () {
                // js 代码实现路由跳转,编程式导航
                my_router.push({name: vm.rName});
            }
        }
    });
</script>

12.6 命名视图

<div id="app-31">
    <div style="width: 100%; height: 20px; background: #00BFFF;">
        <router-link to="/index">t1</router-link>
        <router-link to="/index2">t2</router-link>
        <!-- 路由视图 -->
        <!-- 如果在 HTML 中有一个以上的路由视图 router-view,需要给 router-view 指定 name,
在路由中需要使用 components 映射多个组件根据 name 设置组件与 router-view 的绑定关系 -->
        <router-view name="v1"></router-view>
        <router-view name="v2"></router-view>
    </div>
</div>
<script type="text/javascript">
    <!-- vue 的路由旨在为单页面应用开发提供便携 -->
    // 1. 定义链接跳转的模板(组件)
    const t11 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    t11
    </div>`
    };
    const t12 = {
        template: `<div style="width: 400px; height: 200px; border: red 1px solid" >
                    t12
    </div>`
    };
    const t21 = {
        template: `<div style="width: 400px; height: 200px; border: yellow 1px solid" >
                    t21
    </div>`
    };
    const t22 = {
        template: `<div style="width: 400px; height: 200px; border: wheat 1px solid" >
                    t22
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/index',
                components: {
                    v1: t11,
                    v2: t12
                }
            },
            {
                path: '/index2',
                components: {
                    v1: t21,
                    v2: t22
                }
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-31',
        data: {
            rName: "r1"
        },
        router: my_router,
        methods: {
            test: function () {
                // js 代码实现路由跳转,编程式导航
                my_router.push({name: vm.rName});
            }
        }
    });
</script>

12.7 重定向

12.7.1 重定向

访问 /index, 重定向到 /login

<div id="app-32">
    <router-link to="/login">登录</router-link>
    <router-link to="/index">首页</router-link>
    <router-view></router-view>
</div>
<script type="text/javascript">
    <!-- vue 的路由旨在为单页面应用开发提供便携 -->
    // 1. 定义链接跳转的模板(组件)
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    登录
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/login',
                component: t1
            },
            {
                path: '/index',
                redirect: "/login"
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-32',
        router: my_router
    });
</script>

根据路由命名重定向


// 2. 定义路由

const my_router = new VueRouter({

routes: [

{

path: ‘/login’,

name: “r1”,

component: t1

},

{

path: ‘/index’,

// 根据路由路径重定向

// redirect: “/login”

// 根据路由命名重定向

redirect: {name: “r1”}

}

]

});

12.7.2 路由别名

<div id="app-32">
    <router-link to="/login">登录</router-link><br />
    <router-link to="/alias-login">(别名)-登录</router-link> <br />
    <router-view></router-view>
</div>
<script type="text/javascript">
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    登录
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/login',
                alias: "/alias-login",
                component: t1
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-32',
        router: my_router
    });
</script>

12.8 路由组件传参

可以通过 /url/:attr 方式实现通过路由传值给组件

<div id="app-33">
    <router-link to="/login/101">登录</router-link><br />
    <router-view></router-view>
</div>
<script type="text/javascript">
    const t1 = {
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    登录:{{$route.params.id}}
    </div>`
    };
    // 2. 定义路由
    const my_router = new VueRouter({
        routes: [
            {
                path: '/login/:id',
                component: t1
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-33',
        router: my_router
    });
</script>

通过 props 传参

 <div id="app-33">
     <router-link to="/index/102">首页t2</router-link><br />
     <router-view></router-view>
</div>
<script type="text/javascript">
    const t2 = {
        props:["id"],
        template: `<div style="width: 400px; height: 200px; border: blue 1px solid" >
                    首页t2:{{id}}
    </div>`
    };
    const my_router = new VueRouter({
        routes: [
            {
                path: '/index/:id',
                component: t2,
                props: true
            }
        ]
    });
    // 3. 引用路由
    var vm = new Vue({
        el: '#app-33',
        router: my_router
    });
</script>

af7e4ab24939464bb63413b8f00115f1.png

相关文章
|
6天前
|
缓存 监控 JavaScript
探讨优化Vue应用性能和加载速度的策略
【5月更文挑战第17天】本文探讨了优化Vue应用性能和加载速度的策略:1) 精简代码和组件拆分以减少冗余;2) 使用计算属性和侦听器、懒加载、预加载和预获取优化路由;3) 数据懒加载和防抖节流处理高频事件;4) 图片压缩和选择合适格式,使用CDN加速资源加载;5) 利用浏览器缓存和组件缓存提高效率;6) 使用Vue Devtools和性能分析工具监控及调试。通过这些方法,可提升用户在复杂应用中的体验。
21 0
|
6天前
|
JavaScript 前端开发
vue(1),小白看完都会了
vue(1),小白看完都会了
|
1天前
|
JavaScript Java 关系型数据库
基于SprinBoot+vue的租房管理系统2
基于SprinBoot+vue的租房管理系统2
9 0
|
2天前
|
自然语言处理 JavaScript 数据可视化
5个值得推荐的Vue后台管理框架
几个优秀好看的 Vue 后台管理框架,每个框架都有自己的特点和优势,开发者可以根据项目需求选择适合的框架。
14 0
|
6天前
|
JavaScript 开发工具 git
Vue 入门系列:.env 环境变量
Vue 入门系列:.env 环境变量
13 1
|
6天前
|
JavaScript 前端开发 定位技术
Vue使用地图以及实现轨迹回放 附完整代码
Vue使用地图以及实现轨迹回放 附完整代码
Vue使用地图以及实现轨迹回放 附完整代码
|
6天前
|
JavaScript
Vue中避免滥用this去读取data中数据
Vue中避免滥用this去读取data中数据
|
6天前
|
JavaScript
vue中使用pinia及持久化
vue中使用pinia及持久化
12 0
|
6天前
|
JavaScript 前端开发 UED
Vue class和style绑定:动态美化你的组件
Vue class和style绑定:动态美化你的组件
|
6天前
|
JavaScript 前端开发 API
Vue 监听器:让你的应用实时响应变化
Vue 监听器:让你的应用实时响应变化