1.安装vue-resource。咱们在第一章创建的时候已经安装了 。未安装的可以进入vue项目后
npm install --save vue-resource
安装成功后,可以打开项目的package.json
文件查看所有的配置文件,其中就有vue-resource
的版本信息
2.引入。
使用首先要引入,打开main.js
,输入
import Resource from 'vue-resource'
Vue.use(Resource)
ok,这就引入成功,就可以在组件中写代码使用。
3.使用
打开home.vue
文件,在<script></script>
中输入
export default {
data () {
return {
}
},
component:{
//注册组件
},
mounted:function(){
//生命周期
this.$http.get('http://cangdu.org:8001/v1/cities?type=group').then(response => {
console.log(response);
}, response => {
console.log(response);
});
},
computed:{
//计算属性
},
methods:{
//函数
}
}
return
中用来写需要用到的变量。component
中用来注册本组件需要引用的其他外部组件(用到的时候再说)。mounted
是vue的生命周期,大家都知道页面是有加载顺序的,不是说一下子页面就可以出来。而vue从创建到使用到结束分为了十个周期,称为生命周期钩子,而mounted
是把vue数据加载的html的时候调用(这是我目前的理解)。computed
是计算属性,其中写一个个函数,这些函数用来计算属性,当属性改变时,函数的结果的也会随之改变,而我们使用时只需要调用一次函数即可(用到再说)。methods
中用来写函数,调用一次执行一次。
4.请求
咱们把数据请求放到 mounted
中,vue-resource
代码如下
this.$http.get('http://cangdu.org:8001/v1/cities?type=group').then(response => {
console.log(response);
}, response => {
console.log(response);
});
this
指向vue。数据接口中请求城市列表是GET
请求,所以我们使用this.$http.get()
方法。then
中有两个函数,第一个是请求成功的函数,第二个是请求失败的函数。上面的代码使用了es6
的箭头函数
(我也只是看得懂,并没有用过)
城市的接口地址
数据请求代码这就写完了
在我们的项目中,vue-resource的使用及代码如下
created() {
this.$http.get('./api/seller').then((response) => {
response = response.body;
if (response.errno === ERR_OK) {
this.seller = response.data;
}
});
},
接着,要在data中,将数据传出去
data() {
return {
seller: {}
};
},
在子组件中(header)的props中接收seller,就可以在页面中使用seller了
props: {
seller: {
type: Object
}
},