Ⅶ期VUE的Day2:axios发送http请求、vue生命周期

一、 发送AJAX请求

 1. 简介

    vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现

    axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护

参考:GitHub上搜索axios,查看API文档

2. 使用axios发送AJAX请求

2.1 安装axios并引入

 npm install axios -S

也可直接下载axios.min.js文件

2.2 基本用法

axios([options])  

axios.get(url[,options]);

传参方式:

  1. 通过url传参
  2. 通过params选项传参
axios.post(url,data,[options]);

axios默认发送数据时,数据格式是Request Payload,并非我们常用的Form Data格式,所以参数必须要以键值对形式传递,不能以json形式传参

传参方式:

  1. 自己拼接为键值对
  2. 使用transformRequest,在请求发送前将请求数据进行转换
  3. 如果使用模块化开发,可以使用qs模块进行转换   

    axios本身并不支持发送跨域的请求,没有提供相应的API,作者也暂没计划在axios添加支持发送跨域请求,所以只能使用第三方库

window.onload=function(){
			new Vue({
				el:'#itapp',
				data:{
					user:{
						name:'alice',
						age:19
					},
                    uid:'',
                    loginMsg:{

                    }
				},
				methods:{
                    getUserById(){
                        axios.get(`https://api.github.com/users/${this.uid}`)
						.then(resp => {
							// console.log(resp.data);
							this.loginMsg=resp.data;
						});
                    },
                    sendJSON(){
                        axios({
                            method:'get',
                            url:'user.json',
                            // data:{}
                        }).then((res)=>{
                            console.log(res);
                        }).catch((resp)=>{
                            console.log('请求失败'+resp.status,resp.statusText);
                        })
                    },
                    sendGet(){
                        axios.get('http://localhost:3000/info',{
                            params:{
                                name:'song',
                                age:'10',
                                id:1
                            }
                        }).then((res)=>{
                            console.log(res);
                        }).catch((resp)=>{
                            console.log('请求失败'+resp.status,resp.statusText);
                        })
                    },
                    sendPost(){

                        axios({
                            method:'post',
                            url:'http://localhost:3000/info',
                            data:{
                                name:'song',
                                age:'10',
                                id:1
                            }
                        }).then((res)=>{
                            console.log(res);
                        }).catch((resp)=>{
                            console.log('请求失败'+resp.status,resp.statusText);
                        })

                        // axios.post('http://localhost:3000/info',{
                        //     name:'song',
                        //     age:'10',
                        //     id:1
                        // }).then((res)=>{
                        //     console.log(res);
                        // }).catch((resp)=>{
                        //     console.log('请求失败'+resp.status,resp.statusText);
                        // })


                    },
                    sendPostFormData(){
                        //  axios.post('http://localhost:3000/info','name=alice&age=20') //方式一
                         axios.post('http://localhost:3000/info',this.user,{   //transformRequest转化
                            transformRequest:[
                                function (data) {
                                    // 对 data 进行任意转换处理
                                    // {
                                    //     name:'alice',
                                    //     age:19
                                    // }
                    
                                    // 把json数据转化成formData
                                    var params = '';
                                    for(var index in data) {
                                        params+=index+'='+data[index]+'&'
                                    }
                                    console.log(params)
                                    return params;
                                }
                             ]
                         }) 
                         .then((res)=>{
                            console.log(res);
                        }).catch((resp)=>{
                            console.log('请求失败'+resp.status,resp.statusText);
                        })

                        // 方式三:qs.stringify

                    }
                }
			});
		}
<div id="itapp">
		<button @click="sendJSON">发送AJAX请求</button>

		 <button @click="sendGet">GET方式发送AJAX请求</button>

        <button @click="sendPost">POST方式发送AJAX请求</button>
        
        <button @click="sendPostFormData">POST方式发送AJAX请求  -- FormData</button>
		<hr>
		<br>

		GitHub ID: <input type="text" v-model="uid">
		<button @click="getUserById">获取指定GitHub账户信息并显示</button>
		<br>
		姓名:{{loginMsg.login}} <br>
		头像:<img :src="loginMsg.avatar_url" alt="" style="width:200px;"> 

	</div>

二、Vue生命周期

vue实例从创建到销毁的过程,称为生命周期,共有八个阶段

  • beforeCreate
  • created
  • beforeMount
  • mounted
  • beforeUpdate
  • updated
  • beforeDestroy
  • destroyed

var vm = new Vue({
      el: '#app',
      data: {
        message: 'Vue的生命周期'
      },
      methods:{
        update(){
            this.message = '我改变了数据'
        },
        destroy(){
            this.$destroy(); //组件被销毁以后, 再次对组件进行任何操作都 不起作用了
            // vm.$destroy();
        }
      },
      beforeCreate: function() {
        console.group('------beforeCreate 创建前状态:组件实例刚刚创建,还未进行数据观测和事件配置------');
        console.log("%c%s", "color:red" , "el     : " + this.$el); //undefined
        console.log("%c%s", "color:red","data   : " + this.$data); //undefined 
        console.log("%c%s", "color:red","message: " + this.message)  //undefined
        
      },
      created: function() {
        console.group('------created 创建完毕状态:实例已经创建完成,并且已经进行数据观测和事件配置------');
        console.log("%c%s", "color:red","el     : " + this.$el); //undefined
        console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化 
        console.log("%c%s", "color:red","message: " + this.message); //已被初始化
        
      },
      beforeMount: function() {
        console.group('------beforeMount挂载前状态:模板编译之前,还没挂载------');
        console.log("%c%s", "color:red","el     : " + (this.$el)); //已被初始化
        console.log(this.$el); //模板没有渲染
        console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化  
        console.log("%c%s", "color:red","message: " + this.message); //已被初始化 
         
      },
      mounted: function() {
        console.group('------mounted 挂载结束状态:模板编译之后,已经挂载,此时才会渲染页面,才能看到页面上数据的展示------');
        console.log("%c%s", "color:red","el     : " + this.$el); //已被初始化
        console.log(this.$el);   //模板已经渲染
        console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
        console.log("%c%s", "color:red","message: " + this.message); //已被初始化 
        
      },
      beforeUpdate: function () {
        console.group('beforeUpdate 更新前状态:组件更新之前===============》');
        console.log("%c%s", "color:red","el     : " + this.$el);
        console.log(this.$el);  //还是原来的数据,新数据还没渲染
        console.log("%c%s", "color:red","data   : " + this.$data); 
        console.log("%c%s", "color:red","message: " + this.message); 
        
      },
      updated: function () {
        console.group('updated 更新完成状态:组件更新之后===============》');
        console.log("%c%s", "color:red","el     : " + this.$el);
        console.log(this.$el);  //新数据已经渲染完成
        console.log("%c%s", "color:red","data   : " + this.$data); 
        console.log("%c%s", "color:red","message: " + this.message); 
      },
      beforeDestroy: function () {
        console.group('beforeDestroy 销毁前状态 :组件销毁之前===============》');
        console.log("%c%s", "color:red","el     : " + this.$el);
        console.log(this.$el);    
        console.log("%c%s", "color:red","data   : " + this.$data); 
        console.log("%c%s", "color:red","message: " + this.message); 
        
      },
      destroyed: function () {
        console.group('destroyed 销毁完成状态:组件销毁之后===============》');
        console.log("%c%s", "color:red","el     : " + this.$el);
        console.log(this.$el);  
        console.log("%c%s", "color:red","data   : " + this.$data); 
        console.log("%c%s", "color:red","message: " + this.message)
        
      }
    })
<div id="app">
      <h1>{{message}}</h1>
        <button @click="update">更新数据</button>
		<button @click="destroy">销毁组件</button>
    </div>

参考:详解vue生命周期

 

三、计算属性

1. 基本用法

计算属性也是用来存储数据,但具有以下几个特点:

  • 数据可以进行逻辑处理操作
  • 对计算属性中的数据进行监视

2.计算属性 vs 方法

将计算属性的get函数定义为一个方法也可以实现类似的功能

区别:

  • 计算属性是基于它的依赖进行更新的,只有在相关依赖发生改变时才能更新变化
  • 计算属性是缓存的,只要相关依赖没有改变,多次访问计算属性得到的值是之前缓存的计算结果,不会多次执行

3. get和set

计算属性由两部分组成:get和set,分别用来获取计算属性和设置计算属性。默认只有get,如果需要set,要自己添加

		var vm = new Vue({
			el: '#itapp',
			data: { //普通属性
				msg: 'welcome to itapp',
				num1: 8
			},
			computed: { //计算属性
				msg2: function () {
					//该函数必须有返回值,用来获取属性,称为get函数
					return 'hello';

				},
				reverseMsg() {
					return this.msg.split(' ').reverse().join(' ');
				},
				num2: {
					get() {
						console.log('num2:' + new Date());
						return this.num1 - 1;
					},
					set(val) {
						console.log('修改num2的值');
						this.num1 = val;
					}
				}
			},
			methods: {
				change() {
					this.num2 = 50;
				},
				getNum2() {
					console.log(new Date());
					return this.num1 - 1;
				},
			},
			mounted() {
				// // 多次调取计算属性,可以从缓存获取, 提高性能
				setInterval(function () {
					// console.log(vm.num2); //从缓存获取
					console.log(vm.getNum2());  //每次都要执行函数
				}, 1000);

			}

		});
	<div id="itapp">
		<!-- 
			1.基本用法
		 -->
		<h2>msg: {{msg}}</h2>
		<h2>msg2 :{{msg2}}</h2>

		<!-- 对数据处理再显示 -->
		<h2>msg : {{msg.split(' ').reverse().join(' ')}}</h2>
		<h2>reverseMsg : {{reverseMsg}}</h2>
		<button @click="change">修改计算属性</button>

		<!-- 
			2.计算属性 vs 方法
		 -->
		<h2>num1: {{num1}}</h2>
		<h2>num2 -计算属性 :{{num2}}</h2>
		<h2>getNum 函数: {{getNum2()}}</h2>

		<!-- 
			3.get和set
		 -->
		<!-- <h2>{{num2}}</h2>
		 <button @click="change2">修改计算属性</button> -->


	</div>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值