VueJS - AJAX
Vue AJAX
Vue腳手架配置代理
- 方法一:在
vue.config.js中添加如下配置1
2
3devServer: {
proxy: 'http://localhost:5001'
},- 優點:配置簡單,請求資源時直接發給前端(8080)即可
- 缺點:不能配置多個代理,不能靈活的控制請求是否走代理
- 工作方式:若按照上述配置代理,當請求了前端不存在的資源時,那麼該請求會轉發給服務器(優先匹配前端資源)
- 方法二:編寫
vue.config.js配置具體代理規則1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21devServer: {
proxy: {
'/api1': { // 匹配所有以 '/api1' 開頭的請求路徑
target: 'http://localhost:5001', // 代理目標的基礎路徑
pathRewrite:{'^/api1':''},
ws: true,
changeOrigin: true
},
'/api2': { // 匹配所有以 '/api2' 開頭的請求路徑
target: 'http://localhost:5002', // 代理目標的基礎路徑
pathRewrite:{'^/api2':''},
ws: true,
changeOrigin: true
},
}
}
/*
changeOrigin設置為true時,服務器收到的請求頭中的host為:localhost:5001
changeOrigin設置為false時,服務器收到的請求頭中的host為:localhost:8080
changeOrigin默認值為true
*/- 優點:可以配置多個代理,而且可以靈活的控制請求是否要走代理
- 缺點:配置略微繁瑣,請求資源時必須加前綴
插槽slot
- 作用:
- 默認插槽、具名插槽:讓父組件可以向子組件指定位置插入html結構
- 作用域插槽:可以是一種通信方式,適用於父組件 -> 子組件
- 默認插槽:
- 具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14<!-- 父組件 -->
<template>
<Category>
<div> HTML結構 </div>
</Category>
</template>
<!-- 子組件 -->
<template>
<div>
<!-- 定義插槽 -->
<slot> 插槽默認內容 </slot>
</div>
</template>
- 具體代碼:
- 具名插槽:
- 具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<!-- 父組件 -->
<template>
<Category>
<!-- 方式一 -->
<template slot="slotName1">
<div> HTML結構1 </div>
</template>
<!-- 方式二 -->
<template v-slot:slotName2>
<div> HTML結構2 </div>
</template>
</Category>
</template>
<!-- 子組件 -->
<template>
<div>
<!-- 定義插槽 -->
<slot name="slotName1"> 插槽默認內容 </slot>
<slot name="slotName2"> 插槽默認內容 </slot>
</div>
</template>
- 具體代碼:
作用域插槽
理解:當數據在組件的自身(子組件),但根據數據生成的結構需要組件的使用者(父組件)來決定</font>
具體代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36<!-- 父組件 -->
<template>
<Category>
<template scope="scopeData">
<!-- 生成ul列表 -->
<ul>
<li v-for="(item,index) in scopeData.games" :key="index">{{item}}<li>
</ul>
</template>
</Category>
<Category>
<template scope="scopeData">
<!-- 生成h4標題 -->
<h4 v-for="(item,index) in scopeData.games" :key="index">{{item}}</h4>
</template>
</Category>
</template>
<!-- 子組件 -->
<template>
<div>
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
name:'Category',
props:['title'],
// 數據在子組件中
data(){
return {
games:['a', 'b', 'c' ,'d']
}
}
}
</script>
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.


