第四章:Vue中的ajax
4.1 解决开发环境中Ajax跨域问题
方法一
在vue.config.js
中添加如下配置:
//开启代理服务器(方式一)
devServer:{
proxy:'http://localhost:5000'
}
说明:
- **优点:**配置简单,请求资源时直接发给前端(8080)即可
- **缺点:**不能配置多个代理,不能灵活地控制请求是否走代理
- **工作方式:**若按照上述配置代理,当请求了前端不存在的资源时,那么请求会转发给服务器(优先匹配前端资源)
方法二
编写vue.config.js
配置具体代理规则:
//开启代理服务器(方式二)
devServer:{
proxy:{
'/student':{//匹配所有以'/student'开头的请求路径
target:"http://localhost:5000",//代理目标的基础路径
pathRewrite:{'^/student':''},
ws:true, //用于支持webSocket
changeOrigin:true //默认为true,用于控制请求头中的host值,值为true时,服务器收到的请求头中的host为:localhost:5001,值为true时,服务器收到的请求头中的host为:localhost:8080
},
'car':{//匹配所有以'/car'开头的请求路径
target: "http://localhost:5001",//代理目标的基础路径
pathRewrite:{'^/car':''},
ws:true, //用于支持webSocket
changeOrigin:true //默认为true,用于控制请求头中的host值,值为true时,服务器收到的请求头中的host为:localhost:5001,值为true时,服务器收到的请求头中的host为:localhost:8080
}
}
}
说明:
- **优点:**可以配置多个代理,且可以灵活地控制请求是否走代理
- **缺点:**配置略显繁琐,请求资源时必须加前缀
4.2 github用户搜索案例
main.js
//引入Vue
import Vue from "vue";
//引入App
import App from "./App";
//关闭vue的生产提示
Vue.config.productionTip=false
//创建vm
new Vue({
el:"#root",
render:h=>h(App),
beforeCreate() {
Vue.prototype.$bus=this
}
})
App.vue
<template>
<div class="container">
<Search></Search>
<List></List>
</div>
</template>
<script>
// import 'assets/css/bootstrap.css'
import Search from "./components/Search";
import List from "./components/List";
export default {
name: "App",
components: {List, Search}
}
</script>
<style>
</style>
List.vue
<template>
<div class="row">
<!-- 展示用户列表 -->
<div v-show="info.users.length" class="card" v-for="user in info.users" :key="user.id">
<a :href="user.html_url" target="_blank">
<img :src="user.avatar_url" style='width: 100px'/>
</a>
<p class="card-text">{
{user.login}}</p>
</div>
<!-- 展示欢迎词 -->
<h1 v-show="info.isFirst">欢迎使用!</h1>
<!-- 展示加载中 -->
<h1 v-show="info.isLoading">加载中...</h1>
<!-- 展示错误信息 -->
<h1 v-show="info.errMsg">{
{info.errMsg}}</h1>
</div>
</template>
<script>
export default {
name: "List",
data(){
return {
info:{
isFirst:true,
isLoading:false,
errMsg:"",
users:[]
}
}
},
mounted() {
this.$bus.$on('updateListData',(dataObj)=>{
console.log(dataObj)
this.info={...this.info,...dataObj}
})
},
beforeDestroy() {
this.$bus.$off('updateListData')
}
}
</script>
<style scoped>
.album {
min-height: 50rem; /* Can be removed; just added for demo purposes */
padding-top: 3rem;
padding-bottom: 3rem;
background-color: #f7f7f7;
}
.card {
float: left;
width: 33.333%;
padding: .75rem;
margin-bottom: 2rem;
border: 1px solid #efefef;
text-align: center;
}
.card > img {
margin-bottom: .75rem;
border-radius: 100px;
}
.card-text {
font