vue 笔记

vue3.0

1、创建应用(项目)

使用cnd引入的方式

<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="hello-vue" class="demo">
  {{ message }}
</div>

<script>
const HelloVueApp = {
  data() {
    return {
      message: 'Hello Vue!!'
    }
  },
  methods:{
      log(){
          console.log(this.message);
      }
  }
}
const vueApp = Vue.createApp(HelloVueApp).mount('#hello-vue')  //vue3.0使用createApp函数来创建应用,HelloVueApp将作为应用创建的初始组件。mount('#hello-vue')意思是将创建好的vue应用挂载到id为hello-vue的dom中
vueApp.log(); //Hello Vue!!
</script>
</body>
</html>

使用 npm init vite hello-vue3 – --template vue # 或 yarn create vite hello-vue3 --template vue 创建

image-20220113162300150

2、vue模板语法

插值表达式

<div id="app">
  <p>{{ message }}</p>
</div>

<javaScript>
    export default{
		data(){
            return {
                message: 'hello'
            }
        }
	}
</javaScript>

{{…}} 标签的内容将会被替代为对应组件实例中 message 属性的值,如果 message 属性的值发生了改变,{{…}} 标签内容也会更新。

如果不想改变标签的内容,可以通过使用 v-once 指令执行一次性地插值,当数据改变时,插值处的内容不会更新。

<div id="app">
  <p v-once>{{ message }}</p>
</div>

使用v-once后数据值将不会改变。

v-htm :用于输出html

v-bind:用于绑定html标签的属性值

<div v-bind:id="dynamicId"></div>

v-model

v-model 指令用来在 input、select、textarea、checkbox、radio 等表单控件元素上创建双向数据绑定,根据表单上的值,自动更新绑定的元素的值。

v-on:给dom元素绑定事件

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
    <p>{{ message }}</p>
    <button v-on:click="reverseMessage">反转字符串</button>
</div>
    
<script>
const app = {
  data() {
    return {
      message: 'Runoob!'
    }
  },
  methods: {
    reverseMessage() {
      this.message = this.message
        .split('')
        .reverse()
        .join('')
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>

vue数据绑定图

image-20220112110612024

3、组件

vue注册全局组件

const app = Vue.createApp({'initComponent'}).mount("#domId");

app.component('my-component-name', {
  /* ... */
}) //注册全局组件
// 创建一个Vue 应用
const app = Vue.createApp({})

// 定义一个名为 button-counter 的新全局组件
app.component('button-counter', {
  data() {
    return {
      count: 0
    }
  },
  template: `
    <button @click="count++">
      点了 {{ count }} 次!
    </button>`
})
app.mount('#app')
</script>

注意:template 中 ` 是反引号,不是单单引号 '

局部组件

<div id="app">
    <runoob-a/>
</div>
<script>
var runoobA = {
  template: '<h1>自定义组件!</h1>'
}
 
const app = Vue.createApp({
  components: {
    'runoob-a': runoobA
  }
})
 
app.mount('#app')
</script>

props

props用于接收父组件传递的值

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
  <site-name title="Google"></site-name> //向子组件传值,子组件通过props接收
  <site-name title="Runoob"></site-name>
  <site-name title="Taobao"></site-name>
</div>
 
<script>
const app = Vue.createApp({})
 
app.component('site-name', {
  props: ['title'],
  template: `<h4>{{ title }}</h4>`
})
 
app.mount('#app')
</script>
</body>
</html>

props格式验证

Vue.component('my-component', {
  props: {
    // 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
    propA: Number,
    // 多个可能的类型
    propB: [String, Number],
    // 必填的字符串
    propC: {
      type: String,
      required: true
    },
    // 带有默认值的数字
    propD: {
      type: Number,
      default: 100
    },
    // 带有默认值的对象
    propE: {
      type: Object,
      // 对象或数组默认值必须从一个工厂函数获取
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证函数
    propF: {
      validator: function (value) {
        // 这个值必须匹配下列字符串中的一个
        return ['success', 'warning', 'danger'].indexOf(value) !== -1
      }
    }
  }
})

4、计算属性 computed

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="app">
  <p>原始字符串: {{ message }}</p>
  <p>计算后反转字符串: {{ reversedMessage }}</p>
</div>
    
<script>
const app = {
  data() {
    return {
      message: 'RUNOOB!!'
    }
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () { //默认是取值
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
}
 
Vue.createApp(app).mount('#app')
</script>
  • 计算属性不用在data域中声明,但是计算属性应该依赖与data中某一个属性值,当这个属性值发生改变时,computed也会计算并返回得到的结果。或者也可以通过改变计算属性的值更改data域的属性值。

computer的setter

  • computed属性默认只有 getter ,不过在需要时你也可以提供一个 setter

    var vm = new Vue({
      el: '#app',
      data: {
        name: 'Google',
        url: 'http://www.google.com'
      },
      computed: {
        test: {
          // getter
          get: function () {
            return this.name + ' ' + this.url
          },
          // setter
          set: function (newValue) {
            var names = newValue.split(' ')
            this.name = names[0]
            this.url = names[names.length - 1]
          }
        }
      }
    })
    // 调用 setter, vm.name 和 vm.url 也会被对应更新
    vm.test = 'test';
    document.write('name: ' + vm.name);
    document.write('<br>');
    document.write('url: ' + vm.url);
    

computed与methods的区别

  • computed依赖缓存,只有里面的属性值改变,才会触发相应的get方法进行计算。
  • methodes每次熏染页面函数都会重新调用执行。
  • 使用 computed 性能会更好,但是如果你不希望缓存,你可以使用 methods 属性。

5、watch 监听属性

  • 使用watch可以监听data域属性值的变化
<template>
  <div>
      <!-- <span>{{count}}</span>
      <button @click="count++">click me</button><br> -->
      <span>千米与米换算器</span><br>
      千米:<input v-model="kmeter"/><br>
      米:<input v-model="meter">
  </div>
</template>

<script>
export default {
    data(){
        return{
            count: 0,
            kmeter: 0,
            meter: 0
        }
    },
    watch:{
        count: function(newVal,oldVal){
            console.log('旧值:'+oldVal);
            console.log('新值:'+newVal);
        },
        kmeter:function(newVal){
            this.meter = newVal*1000;
        },
        meter:function(newVal){
            this.kmeter = newVal/1000;
        },
            // watch深度监听:当需要监听一个对象是否改变时,需要使用此方式
       p: {
      	 handler: function (newVal, oldVal) {
        	if(newVal.userName != 'llj' || newVal.userNumber != '2017143128') this.isChange = "改变了";
        	else this.isChange = '没有'
      	 },
      	deep: true
       }
    }
}
</script>

computed与watch的区别

  • computed依赖缓存,watch没有缓存

  • computed里面的异步操作无效,watch支持异步操作

  • watch监听的数据必须是父组件传递的或者是data域里面的数据,computed里面一般定义新的属性

  • computed属性的属性值如果是一个函数,默认此函数为get方法,当依赖属性值改变时就会走set方法

6、样式绑定

<template>
  <div>
      <div :class="{'error':error,'ok':!error}"></div>
      <!-- 可以动态绑定样式 -->
      <div :style="{'background-color':bgColor,width:width+'px',height:height+'px'}"></div>
  </div>
</template>

<script>
export default {
    data(){
        return{
            error: false,
            bgColor: 'yellow',
            width: 100,
            height: 100
        }
    }
}
</script>

<style>
.error{
    background-color: red;
    width: 100px;
    height: 100px;
}
.ok{
    background-color: green;
    width: 100px;
    height: 100px;
}
</style>

如果在父组件想使用子组件定义的class

//子组件
<div  :class="$attrs.class" :style="{height:150+'px','background-color':bgColor}">{{msg}}</div> // 接受父组件的class

//父组件
 <common-child ref="child" :findFather="findFather" class='parentClass'></common-child>

.parentClass{
    background-color: purple;
    font-size: 10px;
    color: red;
    width: 100px;
    height: 100px;
}

7、父子组件方法调用

父组件调用子组件方法

  • 使用 ref

    // 父组件 
    <common-child ref="child" :findFather="findFather" class='parentClass'></common-child>
     <div @click="findChild">{{msg}}</div>
    
     findChild(){
     	this.$refs.child.childMethods('test');
     }
    
    //子组件
      methods:{
         childMethods(args){
             this.msg = 'baba';
             this.bgColor = 'green';
             this.$emit('findFather',null);
         }
      }
    

子组件调用父组件的方法

  • 使用 this.$parent.event()

     this.$parent.findFather(); //子组件
    
     //父组件
     findFather(){
        console.log('ok')
        this.fBgColor = 'red';
        this.msg = '儿子好'
     }
    
  • 使用 this.$emit(‘findFather’,null)

    this.$emit('findFather',null); //子组件
    
     //父组件
     findFather(){
        console.log('ok')
        this.fBgColor = 'red';
        this.msg = '儿子好'
     }
    
  • 使用 :findFather = findFather

    //父组件将方法直接传递给子组件
    <common-child ref="child" :findFather="findFather"></common-child> 
     findFather(){
        console.log('ok')
        this.fBgColor = 'red';
        this.msg = '儿子好'
     }
    //子组件
      props:{
         findFather:{
            type: Function,
            default: null
         }
      }
    this.findFather();
    

8、事件绑定

vue使用v-on来监听dom事件

  • 语法格式

    v-on:click="methodName"
    或
    @click="methodName"
    
  • v-on可以绑定多个方法

    <button @click="one($event), two($event)">
    
  • v-on还提供了事件修饰符

    • .stop - 阻止冒泡
    • .prevent - 阻止默认事件
    • .capture - 阻止捕获
    • .self - 只监听触发该元素的事件
    • .once - 只触发一次
    • .left - 左键事件
    • .right - 右键事件
    • .middle - 中间滚轮事件
<!-- 阻止单击事件冒泡 -->
<a v-on:click.stop="doThis"></a>
<!-- 提交事件不再重载页面 -->
<form v-on:submit.prevent="onSubmit"></form>
<!-- 修饰符可以串联  -->
<a v-on:click.stop.prevent="doThat"></a>
<!-- 只有修饰符 -->
<form v-on:submit.prevent></form>
<!-- 添加事件侦听器时使用事件捕获模式 -->
<div v-on:click.capture="doThis">...</div>
<!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 -->
<div v-on:click.self="doThat">...</div>

<!-- click 事件只能点击一次,2.1.4版本新增 -->
<a v-on:click.once="doThis"></a>
  • v-on的按键修饰符

    <!-- 只有在 keyCode 是 13 时调用 vm.submit() -->
    <input v-on:keyup.13="submit">
    

    记住所有的 keyCode 比较困难,所以 Vue 为最常用的按键提供了别名:

    <!-- 同上 -->
    <input v-on:keyup.enter="submit">
    <!-- 缩写语法 -->
    <input @keyup.enter="submit">
    

    全部的按键别名:

    • .enter
    • .tab
    • .delete (捕获 “删除” 和 “退格” 键)
    • .esc
    • .space
    • .up
    • .down
    • .left
    • .right

    系统修饰键:

    • .ctrl
    • .alt
    • .shift
    • .meta

    鼠标按钮修饰符:

    • .left
    • .right
    • .middle

9、vue表单数据绑定

使用 v-model 双向绑定

  • v-model 会根据控件类型自动选取正确的方法来更新元素。

  • v-model 会忽略所有表单元素的 value、checked、selected 属性的初始值,使用的是 data 选项中声明初始值。

  • v-model 在内部为不同的输入元素使用不同的属性并抛出不同的事件:

    • text 和 textarea 元素使用 value 属性和 input 事件;
    • checkbox 和 radio 使用 checked 属性和 change 事件;
    • select 字段将 value 作为属性并将 change 作为事件。
  • 在文本区域 textarea 插值是不起作用,需要使用 v-model 来代替:

    <!-- 无效 -->
    <textarea>{{ text }}</textarea>
    
    <!-- 有效 -->
    <textarea v-model="text"></textarea>
    
  • 在单选与复选框中使用

    • 在单选框中v-mode只需绑定逻辑值

      <input type="checkbox" id="checkbox" v-model="checked">
          
      data() {
         return {
           checked : false,
         }
      }
      
    • 在复选框中绑定数组

        <input type="checkbox" id="runoob" value="Runoob" v-model="checkedNames">
        <label for="runoob">Runoob</label>
        <input type="checkbox" id="google" value="Google" v-model="checkedNames">
        <label for="google">Google</label>
        <input type="checkbox" id="taobao" value="Taobao" v-model="checkedNames">
            
        data() {
           return {
             checkedNames : []
           }
        }
      
  • 在单选按钮中使用

     <input type="radio" id="runoob" value="Runoob" v-model="picked">
    
     <input type="radio" id="google" value="Google" v-model="picked">
     
      data() {
        return {
          picked : 'Runoob'
        }
      }
    
  • 在下拉列表中使用

      <select v-model="selected" name="fruit">
        <option value="">选择一个网站</option>
        <option value="www.runoob.com">Runoob</option>
        <option value="www.google.com">Google</option>
      </select>
    
      data() {
        return {
          picked : 'Ru'
        }
      }
    
  • 动态绑定选到的值

    <input type="radio" v-model="pick" v-bind:value="a" />
    // 当选中时
    vm.pick === vm.a
    

修饰符

  • lazy

    • v-model 在 input 事件中同步输入框的值与数据,但你可以添加一个修饰符 lazy ,从而转变为在 change 事件中同步

10、自定义指令

使用 directives 选项来注册局部指令

//此时定义的指令时局部的
<template>
 <div>
     <span>{{msg}}</span>
     <input v-focus/>
 </div>
</template>

<script>
export default {
    data(){
        return{
            msg: '自定义页面加载获取焦点的指令: v-focus'
        }
    },
    directives:{
        focus:{
            inserted:function(el){ //在单个vue文件中使用inserted,代表在dom插入时指令生效
                el.focus(); 
            }
        }
    }
}
<div id="app">
    <p>页面载入时,input 元素自动获取焦点:</p>
    <input v-focus>
</div>
 
<script>
const app = {
   data() {
      return {
      }
   },
   directives: {
      focus: {
         // 指令的定义 传统引入方式的html中定义
         mounted(el) {
            el.focus()
         }
      }
   }
}
 
Vue.createApp(app).mount('#app')

指令定义函数提供了几个钩子函数(可选)

  • created: 在绑定元素的属性或事件监听器被应用之前调用。
  • beforeMount: 指令第一次绑定到元素并且在挂载父组件之前调用。。
  • mounted: 在绑定元素的父组件被挂载后调用。。
  • beforeUpdate: 在更新包含组件的 VNode 之前调用。。
  • updated: 在包含组件的 VNode 及其子组件的 VNode 更新后调用。
  • beforeUnmount: 当指令与在绑定元素父组件卸载之前时,只调用一次。
  • unmounted: 当指令与元素解除绑定且父组件已卸载时,只调用一次。

钩子函数的参数有:

el

el 指令绑定到的元素。这可用于直接操作 DOM。

binding

binding 是一个对象,包含以下属性:

  • instance:使用指令的组件实例。

  • value:传递给指令的值。例如,在 v-my-directive="1 + 1" 中,该值为 2

  • oldValue:先前的值,仅在 beforeUpdateupdated 中可用。值是否已更改都可用。

  • arg:参数传递给指令 (如果有)。例如在 v-my-directive:foo 中,arg 为 "foo"

  • modifiers:包含修饰符 (如果有) 的对象。例如在 v-my-directive.foo.bar 中,修饰符对象为 {foo: true,bar: true}

  • dir:一个对象,在注册指令时作为参数传递。例如,在以下指令中。

11、vue路由

router-link

<li :style="{fontSize: style.liFontSize + 'px'}" v-for="(item,index) in linkInfo" :key="index">
    <router-link :to="item.url">{{item.name}}</router-link>
</li>

linkInfo: [{
	'name': '学习wach',
    'url': '/stdWatch'
}]

属性

to 要跳转的url,表示目标路由的链接。 当被点击后,内部会立刻把 to 的值传到 router.push(),所以这个值可以是一个字符串或者是描述目标位置的对象。

replace 设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),导航后不会留下 history 记录。

append 设置 append 属性后,则在当前 (相对) 路径前添加其路径。例如,我们从 /a 导航到一个相对路径 b,如果没有配置 append,则路径为 /b,如果配了,则为 /a/b

tag 有时候想要 <router-link> 渲染成某种标签,例如 <li>。 于是我们使用 tag prop 类指定何种标签,同样它还是会监听点击,触发导航。

event 定义导航事件

active-class 链接被激活时促发的class

router-view

根据url显示对应的视图,下面展示了使用vue的路由机制创建一个单页面应用。

router-view会在原页面上熏染

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/vue-router@4"></script>
</head>
<body>
<div id="app">
  <h1>Hello App!</h1>
  <p>
    <!--使用 router-link 组件进行导航 -->
    <!--通过传递 `to` 来指定链接 -->
    <!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
    <router-link to="/">Go to Home</router-link>
    <router-link to="/about">Go to About</router-link>
  </p>
  <!-- 路由出口 -->
  <!-- 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
</div>

<script>
// 1. 定义路由组件.
// 也可以从其他文件导入
const Home = { template: '<div>Home</div>' }
const About = { template: '<div>About</div>' }
 
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
  { path: '/', component: Home },
  { path: '/about', component: About },
]
 
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = VueRouter.createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
  history: VueRouter.createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})
 
// 5. 创建并挂载根实例
const app = Vue.createApp({})
//确保 _use_ 路由实例使
//整个应用支持路由。
app.use(router)
 
app.mount('#app')
 
// 现在,应用已经启动了!
</script>
</body>
</html>
//app.vue

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

在使用vue-cli创建的项目中,main.js里面声明了一个vue对象并将该对象挂载到 id = ‘app’ 的dom中也就是app.vue,在此页面中使用router-view匹配 url = " / " 的路由,可以导航到不同的页面然后用router-view匹配不同页面构建单页应用。

模块化项目的定义方法

router.js

import { createRouter, createWebHashHistory } from "vue-router"

import about from "./components/about.vue";
import home from "./components/home.vue";



const routes = [ 
  { path: "/home", component: home},
  { path: "/about", component: about }
];



const router = createRouter({
  history: createWebHashHistory(),
  routes
});

export default router;

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'


const app = createApp(App);
app.use(router) //使用路由

app.mount('#app')

app.vue

<template>
  <h1>VUE3.0</h1>
   <router-link to="/home">主页</router-link>
   <hr>
   <router-link to="/about">详情页</router-link>
    <!-- 路由出口 -->
  <!-- 路由匹配到的组件将渲染在这里 -->
  <router-view></router-view>
</template>

12、混入(mixins)

混入定义了一系列的可复用方法或计算属性

定义全局混入对象 vue2.0

//全局混入
const miXin = {
  created(){
    //todo...
    this.fun1()
  },
  methods:{
    fun1(){
      console.log('我是minXin的方法')
    }
  }
};

/* eslint-disable no-new */
new Vue({
  el: '#app',  //挂载到哪个节点
  router, //路由
  components: { App },
  template: '<App/>',
  mixins: [miXin]
})

tips new Vue({…})Vue.createApp({…}) 的区别

模块化的vue项目只支持 new 一次,如果一个项目需要两个vue应用,使用vue无法实现完全隔离。使用 Vue.createApp({...}) api可以实现。

模块化项目中使用混入

const minXin = {
    created(){
        this.sayFun();
    },
    methods:{
        sayFun(){
           console.log('hello , I am a minXin function!!')
        }
    }
};

export default minXin;
import minXin from './miXins/testMiXins';

app.mixin(minXin) //使用全局混入

注意:混入的钩子函数将会在被混入组件钩子函数之前生效。**也就是,先执行混入对象的钩子,再调用组件钩子。**使用全局混入时,混入对象将影响每一个组件。

13,Axios

Axios是一个基于promise封装的HTTP库,用于发送异步请求。

安装

npm i axios

使用

getdata(url){
  axios.get(url).then(res=>{ //使用axios发送get请求
    console.log(res);
  }).catch((e)=>{
    console.log(`异常:${e}`);
  })
}
<template>
  <div>
    <ul v-for="(item,index) in webSite" :key="index">{{item.name}}
      <hr>
      <li v-for="(i,index) in item.info" :key="index">{{i}}</li> 
    </ul>
  </div>
</template>

<script>
import minXin from '../miXins/testMiXins'
export default {
  data(){
    return{
      url: '/api/try/ajax/json_demo.json',
      webSite: []
    }
  },
  created(){
    this.getdata(this.url).then(res=>{
      this.webSite = res.data.sites;
    });
  },
  mixins:[minXin]
}
</script>

tips 使用vite创建的项目配置跨域

  server:{
    port: 8080, //设置启动端口
    open: true, //启动打开网页
    proxy: {
      '/api2': {
        target: 'http://cache.video.iqiyi.com', //目标url
        changeOrigin: true, //设置为true后,本地会形成一个虚拟的代理服务器,跨域的请求由他转发
        rewrite: path => path.replace(/^\/api2/, '') //如果url中有api则替换为''
      },
      '/api': {
          target: 'https://www.runoob.com', //目标url
          changeOrigin: true, //设置为true后,本地会形成一个虚拟的代理服务器,跨域的请求由他转发
          rewrite: path => path.replace(/^\/api/, '') //如果url中有api则替换为''
      }
    }
  }

tips 发送并发请求

    //发送并发请求 
     axios.all([this.getdata(),this.getdata2()]).then(
       axios.spread((acct,perms) => {
         //请求发送完成
       })
     )

通过传递配置的方式创建axios请求

axios(config)

axios({
    url: '',
    method: 'get/post/...',
    data:{//post请求
        username: '',
        password: ''
    }
})

API

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]])

定义axios实列

const axiosInstance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

#实例方法

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]])

请求配置项

  • 除了 url 是必选的,其他都是配置的。如果method没有配置,默认就使用get

    {
        url: '', //请求地址
        method: '', //请求类型  get post put delete
        baseUrl: 'http://sailing.data.com', //baseUrl将自动加在url的前面,除非url是一个绝对的地址
        
        // `transformRequest` 允许在向服务器发送前,修改请求数据
        // 只能用在 "PUT", "POST" 和 "PATCH" 这几个请求方法
        // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
        transformRequest: [function (data) {
        	// 对 data 进行任意转换处理
        	return data;
      	}],
        // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
        transformResponse: [function (data) {
        // 对 data 进行任意转换处理
        	return data;
      	}],
         // `headers` 是即将被发送的自定义请求头
      	headers: {"X-Requested-With": "XMLHttpRequest"},
      	// `params` 是即将与请求一起发送的 URL 参数
      	// 必须是一个无格式对象(plain object)或 URLSearchParams 对象
      	params: {
        	ID: 12345
      	},
       	// `paramsSerializer` 是一个负责 `params` 序列化的函数
       	paramsSerializer: function(params) {
        	return Qs.stringify(params, {arrayFormat: "brackets"})
      	},
       	// `data` 是作为请求主体被发送的数据
       	// 只适用于这些请求方法 "PUT", "POST", 和 "PATCH"
       	// 在没有设置 `transformRequest` 时,必须是以下类型之一:
       	// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
        data: {
          	firstName: "Fred"
      	},
        // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
      	// 如果请求花费了超过 `timeout` 的时间,请求将被中断
      	timeout: 1000,
        // `adapter` 允许自定义处理请求,以使测试更轻松
        // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
        adapter: function (config) {},
        // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
        // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
      	auth: {
        	username: "janedoe",
        	password: "s00pers3cret"
      	},
        // `responseType` 表示服务器响应的数据类型,可以是 "arraybuffer", "blob", "document", "json", "text", "stream"
       	responseType: "json", // 默认的
        // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject  promise 。如果 `validateStatus` 返回 `true` 	(或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
       	validateStatus: function (status) {
        	return status &gt;= 200 &amp;&amp; status &lt; 300; // 默认的
      	},
        // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
      	// 如果设置为0,将不会 follow 任何重定向
      	maxRedirects: 5, // 默认的
        // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
      	// `keepAlive` 默认没有启用
     	httpAgent: new http.Agent({ keepAlive: true }),
      	httpsAgent: new https.Agent({ keepAlive: true }),
        // "proxy" 定义代理服务器的主机名称和端口
      	// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
     	// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
      	proxy: {
        	host: "127.0.0.1",
        	port: 9000,
        	auth: : {
          		username: "mikeymike",
          		password: "rapunz3l"
        	}
      	}
    }
    

    注意:请求的config参数将会优先于配置的默认参数

请求响应结构

{
  // `data` 由服务器提供的响应
  data: {},

  // `status`  HTTP 状态码
  status: 200,

  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: "OK",

  // `headers` 服务器响应的头
  headers: {},

  // `config` 是为请求提供的配置信息
  config: {}
}

拦截器

  • 请求拦截器

    // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
    
  • 响应拦截器

    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        return response;
    }, function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
    });
    
  • 移除拦截器

    var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);
    

错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
    } else {
      // Something happened in setting up the request that triggered an Error
    }
    console.log(error.config);
  });

取消发送

使用 cancel token 取消请求。

var CancelToken = axios.CancelToken;
var source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // 处理错误
  }
});

// 取消请求(message 参数是可选的)
source.cancel('Operation canceled by the user.');

转自: vue3.0-菜鸟教程 笔记整理

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值