网络请求
在
uniapp
中,可以调用uni.request(Object)
方法进行请求网络请求。详情
- 在小程序中,网络相关的API在使用前需要配置域名白名单。
发送 get 请求
methods 默认是 get 请求,如果发送 get 请求,可以不写。详情
<template>
<view>
<button type="default" @click="get">发送get请求</button>
</view>
</template>
<script>
export default {
methods: {,
// 发送get请求
get() {
uni.request({
url: 'http://localhost:8082/api/getlunbo',
methods: 'get',
success (res) {
console.log(res)
}
})
}
}
}
</script>
数据缓存
将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口。
参数名 | 类型 | 必填 | 说明 |
---|---|---|---|
key | String | 是 | 本地缓存中的指定的 key。 |
data | Any | 是 | 需要存储的内容,只支持原生类型、及能够通过 JSON.stringify 序列化的对象。 |
success | Function | 否 | 接口调用成功的回调函数。 |
fail | Function | 否 | 接口调用失败的回调函数。 |
complete | Function | 否 | 接口调用结束的回调函数(调用成功、失败都会执行) |
异步操作
存储到本地缓存
uni.setStorage
存储数据到本地缓存。
<template>
<view>
<button type="default" @click="setStorage">存储数据</button>
</view>
</template>
<script>
export default {
methods: {
// 存储数据到本地缓存
setStorage () {
uni.setStorage({
key: 'id',
data: 80,
success() {
console.log('存储成功')
}
})
}
}
}
</script>
获取本地缓存数据
uni.getStorage
获取本地缓存数据。
<template>
<view>
<button type="default" @click="getStorage">获取数据</button>
</view>
</template>
<script>
export default {
methods: {
// 获取本地缓存数据
getStorage () {
uni.getStorage({
key: 'id',
success(res) {
console.log(res)
}
})
}
}
}
</script>
移除本地缓存数据
uni.removeStorage
移出本地缓存中指定的数据。
<template>
<view>
<button type="default" @click="removeId">获取数据</button>
</view>
</template>
<script>
export default {
methods: {
// 移出本地缓存的Id
removeId () {
uni.removeStorage({
key: 'id',
success() {
console.log('删除成功')
}
})
}
}
}
</script>
同步操作(推荐)
存储到本地缓存
将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口。
<template>
<view>
<button type="default" @click="setStorage">存储数据</button>
</view>
</template>
<script>
export default {
methods: {
// 存储数据到本地缓存
setStorage () {
uni.setStorageSync('id', 100)
}
}
}
</script>
获取本地缓存数据
<template>
<view>
<button type="default" @click="getStorage">获取数据</button>
<button type="default" @click="removeId">移出数据Id</button>
</view>
</template>
<script>
export default {
methods: {
//获取本地缓存的Id
getStorage () {
const id = uni.getStorageSync('id')
console.log(id)
}
}
}
</script>
移除本地缓存的数据
<template>
<view>
<button type="default" @click="removeId">移出数据Id</button>
</view>
</template>
<script>
export default {
methods: {
//获取本地缓存的Id
removeId () {
uni.removeStorageSync('id')
}
}
}
</script>