开发者学堂课程【Vue.js 入门与实战:品牌列表-全局配置数据接口的根域名】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/586/detail/8162
品牌列表-全局配置数据接口的根域名
全局配置数据接口的根域名
每次发起 Ajax 时, getAllList()、add()、del(id) 一共三个,每次前面都带了一个服务器的根地址
'http://vue.studyit.io/api/delproduct/',这样写不便于后期的改造,假如未来服务器的IP地址或域名更换,更换之后几乎每个页面至少要发起一个Ajax请求,由于项目很大需要改很多个域名。
getAllList()、add()、del(id)三次请求中都带着根路径,不写域名地址直接向api发起请求,或只想写/api/getprodlist,因为调用的 get 方法属于 $http,$http 是vue-resource 发展的。
查看 vue-resource 文档中是否有相应的功能——将根路径提取出来,打开浏览器搜索 vue-resource,点开 npm 官网查看 configuration 网页。
Set default values using the global configuration.
的意思是使用全局配置来设置一些默认值。
Vue.http.options.root = '/root';
设置数据 api 接口的根域名。
root 是根的意思,http 是用来发送网络请求的。
设置完根域名后发起每个请求后,http://vue.studyit.io/ 将不用书写直接删掉。
Note that for the root option to work, the path of the request must be relative. This will use this the root option: Vue.http.get('someUrl') while this will not:
的意思是请注意,
要使 root 选项起作用,请求的路径必须是相对的。这将使用根路径选项:Vue.http.get('someUrl'),而这不会提出拼接:Vue.http.get('/someUrl')。
如果在上面启用了服务器请求的数据接口的根地址,下面发起请求是需要使用相对地址。
<script>
// 如果我们通过全局配置了,请求的数据接口 根域名,则,在每次单独发起 http 请求的时候,请求的 url 路径,应该以相对路径开头,前面不能带 / ,否则 不会启用根路径做拼接;
// 设置数据api接口的根域名。
Vue.http.options.root = 'http://vue.atudyit.io/';
// 创建Vue实例,得到ViewMode
var vm = new Vue ({
el:'#app',
data: {
name:'',
list: [ // 存放所有品牌列表的数据
]
},
created() { // 当 vm 实例的 data 和 methods 初始化完毕后,vm 实例会自动执行 created 这个生命周期函数
this.getAllList()
},
methods: {
getAllList() { // 获取所有的品牌列表
// 分析:
//1.由于已经导入了Vue-resource这个包,所以,可以直接通过 this.$http 来发起数据请求
//2.根据接口 API 文档,知道获取列表的时候应该发起一个 get 请求
//3.this.$http.get(‘url’).then(function(result){}
/ /4.当通过 then 指回调函数之后,在回调函数中,可以拿到数据服务器返回的 result
//5.先判断 result.status 是否等于0,如果等于0,就成功了,可以把result.message 赋值给 this.list ;如果不等于0,可以弹框提醒,获取数据失败!
this.$http,get('http://vue.studyit.io/api/getprodlist').then(result => {
// 注意:通过$http 获取到的数据,都在 result.body 中放着
var result = result.body
if (result.status === 0) {
// 成功了
this.getALLlist()
}else{
// 失败了
alert('获取数据失败!')
}
})
},
add() { // 添加品牌列表到后台服务器
this.$http,get('api/addproduct',{name:this.name },{emulateJSON:true }).then(result => {
if (result.status === 0) {
//成功了
//添加完成后,只需要手动,在调用一下getAllList就能刷新品牌列表了
this.getALLlist()
//清空 name
this.name = ''
} else {
//失败了
alert('添加失败!')
}
},
del(id) {
this.$http,get('http://vue.studyit.io/api/delproduct/' + id).then(result => {
if (result.body.status === 0) {
// 删除成功
this.getALLlist()
}else{
alert('删除失败!')
}
})
}
}
});
</script>