需求:因为服务器地址会有变动,所以想让app可以自己修改连接后端地址
设计思路:有一个默认的登录地址,在登录页面增加个设置按钮,点击后可修改地址
进度登录页面判断缓存的地址是否存在不存在则缓存默认地址,将缓存地址赋值给页面url字段,弹窗进行修改,确认修改时修改缓存。
1.登录页面获取缓存地址(账号密码一起)
import { base_url, supply_url } from '@/public/base_url.js'
onLoad() {
const that = this
const account = uni.getStorage({
key: 'account',
success: function (res) {
that.account = res.data
}
})
const password = uni.getStorage({
key: 'password',
success: function (res) {
that.password = res.data
}
})
uni.getSystemInfo({
success(res) {
that.height = res.windowHeight
}
})
if (!uni.getStorageSync('base_url')) {
uni.setStorageSync('base_url', base_url)
}
if (!uni.getStorageSync('supply_url')) {
uni.setStorageSync('supply_url', supply_url)
}
that.baseUrl = uni.getStorageSync('base_url')
that.supplyUrl = uni.getStorageSync('supply_url')
},
2.后面接口调用都用缓存的地址
const base_url = uni.getStorageSync('base_url')
3.页面显示按钮,弹窗,点击获取缓存的数据,保存时替换缓存的地址
<view class="setting" @click="setting">
<image class="settingImg" src="/static/setting.png"></image>
</view>
<uni-popup ref="setUrl" type="center">
<view class="setBody" style="width: 700upx;background-color: #fff;border-radius: 5px;">
<view style="width: 100%;height: 50px;line-height: 50px;text-align: center;font-size: 24px;font-weight: bold;">设置</view>
<uni-row style="height: 50px;line-height: 50px;">
<uni-col :span="8">服务器地址:</uni-col>
<uni-col :span="16">
<input style="width: 100%;height: 50px;line-height: 50px;" type="text" v-model="baseUrl" placeholder="请输入服务器地址" />
</uni-col>
</uni-row>
<uni-row style="height: 50px;line-height: 50px;">
<uni-col :span="8">供应链地址:</uni-col>
<uni-col :span="16">
<input style="width: 100%;height: 50px;line-height: 50px;" type="text" v-model="supplyUrl" placeholder="请输入供应链地址" />
</uni-col>
</uni-row>
<uni-row>
<uni-col :span="12" style="text-align: center;">
<button @click="cancel">取消</button>
</uni-col>
<uni-col :span="12" style="text-align: center;">
<button @click="submit" type="primary">确认</button>
</uni-col>
</uni-row>
</view>
</uni-popup>
4.清除缓存时(例如退出登录、登录失效等)写个公共方法,清除缓存的地方用就行(主要是保留登录信息和url信息)
// 清除所有缓存保留登录信息、url信息
export function clearSession() {
var account = ''
var password = ''
uni.getStorage({
key: 'account',
success: function (res) {
account = res.data
}
})
uni.getStorage({
key: 'password',
success: function (res) {
password = res.data
}
})
const base_url = uni.getStorageSync('base_url')
const supply_url = uni.getStorageSync('supply_url')
uni.clearStorage()
uni.setStorage({
key: 'account',
data: account,
success: function () {
console.log('success');
}
})
uni.setStorage({
key: 'password',
data: password,
success: function () {
console.log('success');
}
})
uni.setStorageSync('base_url', base_url)
uni.setStorageSync('supply_url', supply_url)
}
小记一下。