说明
在 vue 脚手架创建的单文件工程中使用 axios
挂载到vue对象下
修改 main.js 文件,增加下面代码:
import axios from 'axios'
Vue.prototype.$axios=axios;
好处
在其他文件中,可以通过 this.$axios 调用 axios,不需要导入,如下:
this.$axios.get('', {
params: {
name:this.ruleForm.name,
pwd :this.ruleForm.pwd
}
}).then(res => {
alert(res.data.state);
}).catch(err => {
console.log(err);
});
准备数据
在 public 文件件中,创建 json 文件夹,然后创建 student.json 文件,如下:
内容如下图:
{
"name":"李雷",
"age":20,
"sex":"男"
}
代码
修改 HomeView.vue 文件,增加按钮,点击该按钮发送 ajax请求,并将数据显示到页面上
发送get请求
this.$axios.get('json/student.json').then(function(res){
console.log(res);
console.log(res.data);
})
完整代码
<template>
<div class="home">
<br>
<input type="button" value="ajax请求" @click="get"/>
<br>
姓名:{{name}}
<br>
年龄:<span v-text="age"></span>
<br>
性别: <input type="text" v-model="sex" />
</div>
</template>
<script>
export default {
name: 'HomeView',
components: {
},
data:function(){
return {
name:"",
age:undefined,
sex:""
}
},
methods:{
get:function(){
var that = this
this.$axios.get('json/student.json').then(function(res){
console.log(res);
console.log(res.data);
that.name = res.data.name
that.age = res.data.age
that.sex = res.data.sex
})
}
}
}
</script>

