vue异步发送请求,渲染数据

异步请求
html:

<table>
<tr><td>用户名:</td><td><input type="email" name="email"  v-model="email"></td></tr>   //使用双向绑定
<tr><td>密码:</td><td><input type="password" name="password" id="password" v-model="password"></td></tr>
<tr><td colspan="2"><input type="submit" value="登陆" @click="user()"></td></tr>
</table>

script

export default{
		data() {
			return {
				email:'',     #双向绑定
				password:null,
				result:null,
			}
		},

scrip 中js异步请求,写在method中

user() {
    let xhr = new XMLHttpRequest()
    let that=this
    xhr.open('post','http://111.230.10.23/orange/user/login/',true)
    xhr.setRequestHeader('content-type','application/x-www-form-urlencoded');#post参数请求说明
    xhr.send("email="+this.email+"&password="+this.password);//传递参数
    xhr.onreadystatechange = function(){
        	if (xhr.status==200 && xhr.readyState==4){       //获取返回成功的数据
    		let res = xhr.responseText
    		res=JSON.parse(res)
        		console.log(res)
    		if (res.code==1){
    			that.$router.push({path:'/info'})   #跳转路由vue中
                           window.localhost.href = '/info/'     #js跳转
                           window.open('/info/')     #window跳转
                    }
            }
    }		
}	 

vue,script的ajax写法,首先要使用Axios重新定义ajax

import Axios from 'axios'
Vue.prototype.$ajax = Axios 

然后ajax可以这么写

user(){
    let that=this
    var qs = require('qs');
    var  params= new URLSearchParams();  #post请求传参需要这么写,指明类型
    params.append('email', this.email);
    params.append('password', this.password);
    this.$ajax.post('http://111.230.10.23/orange/user/login/',params)
    .then(response => (that.$router.push({path:'/info'})))
    .catch(err => (console.log('错误提示:' + err),console.log(456)))
    }
			
},

数据渲染时,进入页面就直接渲染
template中

<div>
		<img :src="icon" alt="">
		<p>昵称:{{ name }}</p>
		<p>签名:{{ info }}</p>
		<p>性别:{{ sex }}</p>
		<p>ID号:{{ id }}</p>
	</div>

script中

export default{
		data(){
			return{
				icon:'',
				sex:'',
				name:'',
				info:'',
				id:'',
			}
		},

进入则直接调用渲染函数

mounted:function(){
    this.showdate();
    },
methods: {
    showdate() {
        this.$ajax.get('http://111.230.10.23/orange/user/info/')     #vue中的ajax写法
        .then(response => (console.log(response.data)))
        .catch(err => (console.log('错误提示:' + err)))
    }
},

使用钩子函数

created(){
    this.$ajax.get('http://111.230.10.23/orange/user/info/')
    .then(response => (this.name=response.data.user[0].name,
                        this.id=response.data.user[0].id))
    .catch(err => (console.log('错误提示:' + err)))
    }
}