当前位置: 首页 > news >正文

孙卫琴的《精通Vue.js》读书笔记-在Vue项目中使用Axios

本文参考孙卫琴,杜聚宾所创作的 <<精通Vue.js: Web前端开发技术详解>>一书
在这里插入图片描述
为了在Vue项目中使用Axios,首先要安装Axios插件,还有可选的Vue-Axios插件。Vue-Axios插件能够把Axios与Vue更方便地整合在一起,允许组件通过this.axios的形式来访问Axios。
对于helloworld项目,在DOS命令行转到helloworld根目录下,运行以下命令,就会安装Axios和Vue-Axios插件:

npm install axios vue-axios

在src/main.js中引入Axios和Vue-Axios插件,参见例程1。

例程1 main.js

import {createApp } from 'vue'
import App from './App.vue'
import router from './router'
import  axios from 'axios'
import VueAxios from  'vue-axios'

const app = createApp(App)
app.use(router)
app.use(VueAxios,axios)
app.mount('#app')

接下来在Vue组件的代码中就可以通过this.axios的形式来访问Axios了。

1. 异步请求

例程2的GetCustomer.vue定义了GetCustomer组件,它根据用户输入的id,到服务器端查询匹配的customer对象,把它显示到网页上。

例程2 GetCustomer.vue

<template>
  <div>
    <p>输入id: <input v-model="customer.id" />  
       <button @click="getCustomer">查询</button>  {{msg}} </p>  
    <p> {{isLoading}}</p>
    <p>名字:{{customer.name}} </p>
    <p>年龄:{{customer.age}} </p>
  </div>
</template>
  
<script>
  export default {
    data(){
      return {
        customer: {id: '', name: '', age: ''},
        msg: '',
        isLoading: ''
      }
    },
    
    methods: {
      getCustomer(){
        this.customer.name=''
        this.customer.age=''
        this.msg=''
        this.isLoading='正在查询...'
        this.axios({
          baseURL: 'http://www.javathinker.net',
          url: '/customer',
          method: 'get',
          params: {id: this.customer.id}
        }).then( (response)=> {
          this.isLoading=''
          if(response.data !== null){
            this.customer=response.data
          }else
            this.msg='未找到匹配的数据!'
        }).catch( (error) =>{
          this.isLoading=''
          console.log(error)
        })
      }
    }
  }
</script>

在GetCustomer组件的getCustomer()方法中,通过axios()函数来发出Ajax请求:

this.axios({   //返回Promise对象
  baseURL: 'http://www.javathinker.net',
  url: '/customer',
  method: 'get',
  params: {id: this.customer.id}
})

以上axios()函数的参数是一个请求配置对象,在该请求配置对象中,baseURL属性表示根URL、url属性表示相对URL,method属性表示请求方式,params属性表示请求参数(也称为查询参数),以上代码也可以简写为:

this.axios
    .get('http://www.javathinker.net/customer?id='+this.customer.id)

在src/router/index.js中,为GetCustomer组件设置的路由的路径为“/getcustomer”。通过浏览器访问“http: //localhost:8080/#/getcustomer”,在网页的id输入框中输入1,然后点击“查询”按钮,会看到网页上先显示提示信息“正在查询…”,接下来再显示相应的customer对象的信息,参见图1。
在这里插入图片描述

图1 查询id为1的customer对象

如果在网页的id输入框中输入5,然后点击“查询”按钮,会看到网页上先显示提示信息“正在查询…”,接下来显示“未找到匹配的数据!”。
在GetCustomer组件的getCustomer()方法中,先把isLoading变量设为“正在查询…”,接下来再调用axios()函数。axios()函数会异步请求访问服务器:

       this.isLoading='正在查询...'
       this.axios({
         ……
       }).then( (response)=> {
         this.isLoading=''
         ……
       }).catch( (error) =>{
         this.isLoading=''
         ……
       })

在浏览器与服务器进行异步通信的过程中,浏览器的主线程会继续运行,刷新网页上的{{isLoading}}插值表达式,显示当前值“正在查询…”。等到浏览器与服务器的通信结束,浏览器端接收到了响应结果,就会执行then()函数,把isLoading变量的值改为“”,并且如果response.data不为null,还会把response.data赋值给customer变量。Vue框架的响应式机制会同步刷新网页上的{{isLoading}}、{{customer.name}}和{{customer.age}}插值表达式。

Promise对象的then()函数的返回值仍然是Promise对象,它会异步执行then()函数的参数指定的函数。以下代码表面上看,是把响应正文显示到网页上:

<template>
  <div>{{content}} </div>
</template>

<script>
  ……
  mounted(){
    let result={}

    this.axios.get('http://www.javathinker.net/customer?id=1')
    .then(response=>{
      result=response.data      
    })

    this.content=result  
  }
  ……
</script>

实际上,以上代码中的赋值语句的执行顺序为:

let result={}
this.content=result
result=response.data

因此,网页上的{{result}}表达式的值始终为{}。

2.POST请求方式

例程3的Calculate.vue定义了Calculate组件,它会把用户输入的变量x和变量y通过POST请求方式传给服务器,服务器返回x+y的运算结果,Calculate组件再把运算结果显示到网页上。

例程3 Calculate.vue

<template>
  <div id="app">
    <p>输入变量x: <input v-model.number="x" />  </p>
    <p>输入变量y: <input v-model.number="y" />  </p>
    <button @click="add">计算</button>  
    <p>{{result}}</p>

  </div>
</template>
  
<script>
  export default {
    data(){
      return {
        x: 0, y: 0, result: ''
      }
    },
    
    methods: {
      add(){
        this.axios.post(   //采用POST请求方式
          'http://http://www.javathinker.net/add',
          'x='+this.x+'&y='+this.y   //请求正文
        ).then( response=> {
          this.result=this.x+'+'+this.y+'='+response.data
        }).catch( error =>{
          console.log(error)
        })
      }
    }
  }
</script>

GetCustomer组件的add()方法通过axios.post()函数来指定请求方式为POST,该函数等价于以下axios()函数:

       this.axios({
         baseURL: 'http://www.javathinker.net',
         url: '/add',
         method: 'post',   //指定POST请求方式
         data: 'x='+this.x+'&y='+this.y   //请求正文
       })

在src/router/index.js中,为Calculate组件设置的路由的路径为“/calculate”。通过浏览器访问“http: //localhost:8080/#/calculate”,在网页的变量x和变量y的输入框中分别输入数字,然后点击“计算”按钮,add()方法就会请求服务器计算x+y,再把运算结果显示到网页上,参见图2。
在这里插入图片描述

图2 Calculate组件的网页

相关文章:

  • java多线程 -- volatile 关键字 内存 可见性
  • Solaris 9 Sparc下安装整合Apache2和Tomcat5
  • axis和axis2的一些发布差异(WSDL2Java)
  • 孙卫琴的《精通Vue.js》读书笔记-组件的递归
  • 微信支付服务商模式(电商收付通)实现分账操作
  • LeetCode 946 验证栈序列[栈 模拟] HERODING的LeetCode之路
  • 第十七天计算机视觉之光学字符识别基础理论
  • 混迹职场10多年的数据开发老鸟,居然被一个职场新人上了一课
  • PHP - AJAX 与 PHP
  • 微服务项目调用外部接口
  • 【Python】第八课 异常处理
  • Atomic Mail Sender 9.6.X 中文版Crack
  • 【重识云原生】第六章容器6.1.4节——Docker核心技术LXC
  • mysql—自增长和索引
  • 【C语言】带你深入剖析字符串相关知识(详细讲解+源码展示)
  • “Material Design”设计规范在 ComponentOne For WinForm 的全新尝试!
  • 【Redis学习笔记】2018-06-28 redis命令源码学习1
  • E-HPC支持多队列管理和自动伸缩
  • go append函数以及写入
  • Idea+maven+scala构建包并在spark on yarn 运行
  • Java精华积累:初学者都应该搞懂的问题
  • Rancher-k8s加速安装文档
  • rc-form之最单纯情况
  • 程序员最讨厌的9句话,你可有补充?
  • 分类模型——Logistics Regression
  • 如何将自己的网站分享到QQ空间,微信,微博等等
  • 我的面试准备过程--容器(更新中)
  • 赢得Docker挑战最佳实践
  • scrapy中间件源码分析及常用中间件大全
  • 没有任何编程基础可以直接学习python语言吗?学会后能够做什么? ...
  • ​Distil-Whisper:比Whisper快6倍,体积小50%的语音识别模型
  • "无招胜有招"nbsp;史上最全的互…
  • #HarmonyOS:Web组件的使用
  • #Linux杂记--将Python3的源码编译为.so文件方法与Linux环境下的交叉编译方法
  • $Django python中使用redis, django中使用(封装了),redis开启事务(管道)
  • (6)STL算法之转换
  • (附源码)ssm本科教学合格评估管理系统 毕业设计 180916
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (十五)使用Nexus创建Maven私服
  • (原創) 博客園正式支援VHDL語法著色功能 (SOC) (VHDL)
  • (转)fock函数详解
  • (轉貼) 2008 Altera 亞洲創新大賽 台灣學生成果傲視全球 [照片花絮] (SOC) (News)
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • .net用HTML开发怎么调试,如何使用ASP.NET MVC在调试中查看控制器生成的html?
  • [ vulhub漏洞复现篇 ] ThinkPHP 5.0.23-Rce
  • [1127]图形打印 sdutOJ
  • [BZOJ 4598][Sdoi2016]模式字符串
  • [C++]类和对象(中)
  • [ComfyUI进阶教程] animatediff视频提示词书写要点
  • [DM复习]Apriori算法-国会投票记录关联规则挖掘(上)
  • [IE6 only]关于Flash/Flex,返回数据产生流错误Error #2032的解决方式
  • [Kubernetes]9. K8s ingress讲解借助ingress配置http,https访问k8s集群应用
  • [leetcode] 3Sum
  • [leetcode] 66. 加一
  • [Leetcode] Permutations II