千锋 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

相关文章
|
23天前
|
人工智能 JavaScript 算法
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
Vue 中 key 属性的深入解析:改变 key 导致组件销毁与重建
163 0
|
24天前
|
JavaScript UED
用组件懒加载优化Vue应用性能
用组件懒加载优化Vue应用性能
|
1月前
|
JavaScript 前端开发 开发者
Vue 自定义进度条组件封装及使用方法详解
这是一篇关于自定义进度条组件的使用指南和开发文档。文章详细介绍了如何在Vue项目中引入、注册并使用该组件,包括基础与高级示例。组件支持分段配置(如颜色、文本)、动画效果及超出进度提示等功能。同时提供了完整的代码实现,支持全局注册,并提出了优化建议,如主题支持、响应式设计等,帮助开发者更灵活地集成和定制进度条组件。资源链接已提供,适合前端开发者参考学习。
142 17
|
1月前
|
监控 JavaScript 前端开发
Vue 文件批量下载组件封装完整使用方法及优化方案解析
本文详细介绍了批量下载功能的技术实现与组件封装方案。主要包括两种实现方式:**前端打包方案(基于file-saver和jszip)** 和 **后端打包方案**。前者通过前端直接将文件打包为ZIP下载,适合小文件场景;后者由后端生成ZIP文件流返回,适用于大文件或大量文件下载。同时,提供了可复用的Vue组件`BatchDownload`,支持进度条、失败提示等功能。此外,还扩展了下载进度监控和断点续传等高级功能,并针对跨域、性能优化及用户体验改进提出了建议。可根据实际需求选择合适方案并快速集成到项目中。
165 17
|
1月前
|
JavaScript 前端开发 UED
Vue 手风琴实现的三种常用方式及长尾关键词解析
手风琴效果是Vue开发中常见的交互组件,可节省页面空间、提升用户体验。本文介绍三种实现方式:1) 原生Vue结合数据绑定与CSS动画;2) 使用Element UI等组件库快速构建;3) 自定义指令操作DOM实现独特效果。每种方式适用于不同场景,可根据项目需求选择。示例包括产品特性页、后台菜单及FAQ展示,灵活满足多样需求。附代码示例与资源链接,助你高效实现手风琴功能。
103 10
|
1月前
|
JavaScript 前端开发 UED
Vue 表情包输入组件的实现代码:支持自定义表情库、快捷键发送和输入框联动的聊天表情解决方案
本文详细介绍了在 Vue 项目中实现一个功能完善、交互友好的表情包输入组件的方法,并提供了具体的应用实例。组件设计包含表情分类展示、响应式布局、与输入框的交互及样式定制等功能。通过核心技术实现,如将表情插入输入框光标位置和点击外部关闭选择器,确保用户体验流畅。同时探讨了性能优化策略,如懒加载和虚拟滚动,以及扩展性方案,如自定义主题和国际化支持。最终,展示了如何在聊天界面中集成该组件,为用户提供丰富的表情输入体验。
115 8
|
1月前
|
JavaScript 前端开发 UED
Vue 表情包输入组件实现代码及详细开发流程解析
这是一篇关于 Vue 表情包输入组件的使用方法与封装指南的文章。通过安装依赖、全局注册和局部使用,可以快速集成表情包功能到 Vue 项目中。文章还详细介绍了组件的封装实现、高级配置(如自定义表情列表、主题定制、动画效果和懒加载)以及完整集成示例。开发者可根据需求扩展功能,例如 GIF 搜索或自定义表情上传,提升用户体验。资源链接提供进一步学习材料。
78 1
|
1月前
|
JavaScript API 开发者
Vue框架中常见指令的应用概述。
通过以上的详细解析,你应该已经初窥Vue.js的指令的威力了。它们是Vue声明式编程模型的核心之一,无论是构建简单的静态网站还是复杂的单页面应用,你都会经常用到。记住,尽管Vue提供了大量预定义的指令,你还可以创建自定义指令以满足特定的需求。为你的Vue应用程序加上这些功能增强器,让编码变得更轻松、更愉快吧!
35 1
|
1月前
|
存储 JavaScript 前端开发
如何高效实现 vue 文件批量下载及相关操作技巧
在Vue项目中,实现文件批量下载是常见需求。例如文档管理系统或图片库应用中,用户可能需要一次性下载多个文件。本文介绍了三种技术方案:1) 使用`file-saver`和`jszip`插件在前端打包文件为ZIP并下载;2) 借助后端接口完成文件压缩与传输;3) 使用`StreamSaver`解决大文件下载问题。同时,通过在线教育平台的实例详细说明了前后端的具体实现步骤,帮助开发者根据项目需求选择合适方案。
95 0
|
1月前
|
JavaScript 前端开发 UED
Vue 项目中如何自定义实用的进度条组件
本文介绍了如何使用Vue.js创建一个灵活多样的自定义进度条组件。该组件可接受进度段数据数组作为输入,动态渲染进度段,支持动画效果和内容展示。当进度超出总长时,超出部分将以红色填充。文章详细描述了组件的设计目标、实现步骤(包括props定义、宽度计算、模板渲染、动画处理及超出部分的显示),并提供了使用示例。通过此组件,开发者可根据项目需求灵活展示进度情况,优化用户体验。资源地址:[https://pan.quark.cn/s/35324205c62b](https://pan.quark.cn/s/35324205c62b)。
45 0