在vue中ajax()方法被封装成vue-resource插件,通过在项目中引入该插件,然后调用该插件的的方法或者属性,实现与服务器的通信。
1、首先,在项目中安装本地的vue-resource:假设项目的整个框架已经安装完成,这时候只需要在本地安装vue-resource插件
在cmd中输入“npm install vue-resource --save”
2、安装完成以后,在src/main.js文件中加上下面两句话,就可以使用vue-resource的方法以及属性了
import VueResource from 'vue-resource';
Vue.use(VueResource);
使用vue-resource插件中使用http对象实现与后台的交互,可以参考官方文档:点击打开链接
点击“HTTP Request/Response”选项,可以看到http的一些属性以及方法
3、在App.vue中使用http中的get()方法,实现与后台的通信
//在生命周期函数中去拿到后台返回的数据,这里利用钩子函数created()
created(){
this.$http.get('/api/seller').then((res) => {//通过get()方法想后台发送请求
res = res.body; //返回的数据
if( res.errno === ERR_OK ){ //判断请求是否成功,ERR_OK是一个常量,用于判断请求的状态
//请求成功
this.seller = res.data;
console.log(this.seller);
}
});
}
App.vue中<script>标签中完整的js代码如下
<script>
import header from './components/header/header.vue';
const ERR_OK = 0; //定义一个常量,便于管理
export default {
name: 'App',
data(){
return {
seller:{} //在data方法中定义一个接受从后台返回数据的对象
}
},
//在生命周期函数中去拿到后台返回的数据,这里利用钩子函数created()
created(){
this.$http.get('/apiller').then((res) => {
res = res.body;
if( res.errno === ERR_OK ){
//请求成功
this.seller = res.data; //修改seller的值
console.log(this.seller);
}
});
},
components:{
'v-header':header
}
}
</script>