vue–数据请求
axios:
1.静态请求:
getStatic () {
axios({
url: './mock/data.json',
method: 'GET'
}).then( *res* => console.log( res ))
.catch( *err* => console.log( err ))
`}
2.动态数据 - 接口 - get:
get () {*
this.$http({
url: 'http://localhost:3000/shop',
params: {
a: 1,
b: 2
}
}).then( *res* => console.log( res ))
.catch( *err* => console.log( err ))
`}
3.动态数据 - 接口 - post:
post () {
const params = new URLSearchParams()
params.append(‘firstName’,‘Gabriel’)
params.append(‘lastName’,‘Yan’)
axios({
method: ‘POST’,
url: ‘http://localhost:3000/shop’,
data: params
});
}
4.数据请求 vue-resoure
*
new Vue({
el: '#app',
methods: {
getStatic () {
this.$http({
url: './mock/data.json',
}).then( *res* => console.log( res ))
.catch( *err* => console.log( err ))
}
}
})
5.数据请求 fetch
new Vue({
el: '#app',
methods: {
getStatic () {
fetch('./mock/data.json')
.then( data => data.json())
.then( res => console.log( res ))
.catch( err => console.log( err ))
},
get () {
// 将一个对象转成url字符 , 用node中 url模块来完成
fetch('http://localhost:3000/shop?a=1&b=2')
.then( data => data.text())
.then( res => console.log( res ))
.catch( err => console.log( err ))
},
post () {
// 通过fetch获取百度的错误提示页面
fetch('http://localhost:3000/shop', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式为表单提交
}),
body: new URLSearchParams([["foo", 1],["bar", 2]]).toString()
})
.then((res)=>{
return res.text()
})
.then((res)=>{
console.log(res)
})
}
}
})
6.使用场景:
方法:methods:如果是事件处理程序
侦听属性:watch:如果是由某一个数据改变引起新的异步数据请求
计算属性:computed:如果有逻辑处理,但是将来使用类似于变量,里面放的都是方法。
侦听属性:
new Vue({
el: '#app',
data: {
firstName: '',
lastName: '',
fullName: ''
},
watch: {
*//watch是一个对象*
*// watch里面存储的类型: 方法,对象,普通字符*
firstName ( *val* ) {*//方法的名称和data选项中的key相同,是谁就监听谁*
console.log( val )
console.log('firstName发生了改变')
this.fullName = val + this.lastName
},
lastName ( *val* ) {
this.fullName = this.firstName + val
}
}
})