生命周期函数和Axios网络请求

本文介绍了Vue组件的生命周期函数,强调了在不同阶段放置网络请求以优化用户体验。同时,详细展示了如何在组件内局部引用和全局引用Axios进行GET和POST请求。通过在main.js中挂载到Vue实例,实现了全局使用$axios。
摘要由CSDN通过智能技术生成

生命周期函数

<template>
	<div>
		<h1>生命周期函数</h1>
		<p>{{message}}</p>
		<button @click="message='b'">a->b</button>
	</div>
</template>
<script>
	export default {
		name: "mycomponent",
		data() {
			return {
				message:"a"
			}
		},
		beforeCreate() {
			console.log("组件创建前")
		},
		created() {
			console.log("组件创建后")
			//网络请求放在这里提高用户体验,但是消耗网络
		},
		beforeMount() {
			console.log("组件渲染前")
		},
		mounted() {
			console.log("组件渲染后")
			//一般用来放网络请求
		},
		beforeUpdate() {
			console.log("组件更新前")
		},
		updated() {
			console.log("组件更新后")
		},
		beforeUnmount() {
			console.log("组件卸载前")
			//卸载之前把消耗性能的都处理掉
			//定时器
		},
		unmounted() {
			console.log("组件卸载后")
		}
	}
</script>

Axios网络请求

局部引用

使用npm安装: 
npm install axios
npm install -save querystring //post用来处理参数格式的工具
组件中引入: 
import axios from 'axios'
import querystring from 'querystring'
// get请求方式
axios({
		method: "get",
		url: "http://123.207.32.32:8000/home/multidata"
	}).then(res => {
		this.getValue = res.data.data.banner.list[0]
	})
//get快捷
axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
	console.log(res.data)
})
// post请求方式
// axios({
// 	method: "post",
// 	url: "http://iwenwiki.com/api/blueberrypai/login.php",
// 	data:querystring.stringify({
// 		user_id: 'iwen@qq.com',
// 		password: 'iwen123',
// 		verification_code: 'crfvw'
// 	})
// }).then(res => {
// 	console.log(res.data)
// })

//post快捷
axios.post("http://iwenwiki.com/api/blueberrypai/login.php", querystring.stringify({
	user_id: 'iwen@qq.com',
	password: 'iwen123',
	verification_code: 'crfvw'
})).then(res => {
	console.log(res.data)
})

全局引用

//在src文件夹下的main.js里引入axios
import axios from 'axios'

// 与Vue实例关联(定义$axios为axios)
Vue.prototype.$axios = axios

//其他页面引用方式:不需要导入,直接应用
this.$axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
	console.log(res.data)
	})
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值