第四章-Vue中的Ajax
1、跨域问题
- xhr new XMLHttpRequest() xhr.open() xhr.close()
- jQuery $.get $.post
- axios
- fetch
跨域:
-
cors
-
jsonp
-
代理服务器
- nginx
- vue-cli
-
vue.config.js
module.exports = {
devServer: {
// 开启代理服务器
proxy: {
'/makeid-boot':{ //匹配所有以'/makeid-boot'开头的路径
target: 'http://localhost:8085',
ws: true, //用于支持websocket
changeOrigin: true, // 允许跨域
// pathRewrite:{} //重写路径
}
}
}
}
- 错误
When
proxy
in package.json is an object, eachconte xt
object must have atarget
property specified as
a url string
target写成了url
<template>
<div>
<button @click="getStudent">获取学生信息</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: "App",
components:{
},
methods:{
getStudent(){
axios({
headers:{'token':'9b2cf68b95432f69abe55f77922e5a7f'},
methods: 'get',
url:'http://localhost:8081/makeid-boot/asset/tasset/info/1',
}).then(response => {
console.log(JSON.stringify(response.data.result))
},
error => {
console.log('请求失败',error)
})
}
}
}
</script>
<style scoped>
</style>
- 直接配置,端口号后面不能跟地址
module.exports = {
devServer: {
proxy: 'http://localhost:8085'
}
}
- config.js中配置
2、vue-resource
发送请求
下载npm i vue-resource
main.js
import VueResource from 'vue-resource'
Vue.config.productionTip = false;
Vue.mixin(mixin)
// const Demo=Vue.extend({})
// const d = new Demo
// Vue.prototype.x= d
// 使用插件
Vue.use(VueResource)
this.$http({
headers:{'token':'9b2cf68b95432f69abe55f77922e5a7f'},
methods: 'get',
url:'http://localhost:8081/makeid-boot/asset/tasset/info/1',
}).then(response => {
console.log(JSON.stringify(response.data.result))
},
error => {
console.log('请求失败',error)
})
vue1.0使用较多
3、slot插槽
-
不使用插槽
-
默认插槽
student.vue
<template> <div> <p>学生名称:{{name}}</p> <p>学生地址:{{address}}</p> <p>学生年龄:{{age}}</p> <!-- 定义一个插槽--> <slot>我是默认值</slot> </div> </template>
App.vue
<template> <div> <Student> <p>我是插槽</p> </Student> </div> </template>
-
具名插槽
App.vue
<template> <div> <Student> <p slot="center">我是插槽</p> <p slot="footer">具名插槽</p> </Student> </div> </template>
Student.vue
<template> <div> <p>学生名称:{{name}}</p> <p>学生地址:{{address}}</p> <p>学生年龄:{{age}}</p> <!-- 定义一个插槽--> <slot name="center">我是默认值</slot> <slot name="footer">我是默认值</slot> </div> </template>
-
作用域插槽
App.vue
<template> <div> <Student> <p slot="center">我是插槽</p> <p slot="footer">具名插槽</p> <template scope="name"> <p>{{name.game}}</p> </template> <!-- 不行--> <template scope="{game}"> <p>game</p> </template> <template slot-scope="{game}"> <p>game</p> </template> </Student> </div> </template>
<template> <div> <p>学生名称:{{name}}</p> <p>学生地址:{{address}}</p> <p>学生年龄:{{age}}</p> <!-- 定义一个插槽--> <slot name="center">我是默认值</slot> <slot name="footer">我是默认值</slot> <slot :game="game"></slot> </div> </template>