这个小节里,我们要通过和后端数据交互实现一个登录的功能。
这里我们要用到vue-resource,vue-resouce就相当于jQuery的$.ajax,是用来访问后端数据的。
安装
npm install vue-resource
简单调用
在main.js中引用vue-resource
import VueResource from 'vue-resource'
Vue.use(VueResource)
在Login.vue中改写login方法
login:function(){
this.$http.get('http://*****/authenticate/credentials'
,{
params:{
UserName : this.username,
Password : this.password
}
})
.then(
response => {
this.message = '';
router.push({path:'/main'});
}
,response =>{
this.message = '用户名或密码错误';
}
);
}
全局root url
Vue.use(VueResource);
Vue.http.options.root = 'http://****';
然后在login方法中
this.$http.get('authenticate/credentials')
开发和生产环境
我们的开发环境API和生产环境API往往是分开的。我们下面用webpack给开发环境和生产环境配置不同的接口地址。
首先我们找到下面的文件:
/config/dev.env.js
/config/prod.env.js
这两个文件就是针对开发环境和生产环境设置不同参数的文件。
我们先打开dev.env.js,修改一下开发环境的配置。在module.exports加入一行
API_ROOT: '"http://***"'
类似的我们再修改一下prod.env.js。
在main.js中调用设置好的参数。
Vue.http.options.root = process.env.API_ROOT