UniApp Login: Store User Data Securely
In UniApp, you can use the uni.setStorageSync(key, data) method to store user information and the uni.getStorageSync(key) method to retrieve the stored user information. Here is a simple example code for storing user information during login.
- Create a login page with input fields for username and password, as well as a login button.
<template>
<view>
<input v-model="username" placeholder="请输入用户名"></input>
<input v-model="password" placeholder="请输入密码" type="password"></input>
<button @tap="login">登录</button>
</view>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
};
},
methods: {
login() {
// 进行登录验证
// ...
// 登录成功后存储用户信息
const userInfo = {
username: this.username,
password: this.password,
// 其他用户信息...
};
uni.setStorageSync('userInfo', userInfo);
// 跳转到其他页面
uni.navigateTo({
url: '/pages/home/home',
});
},
},
};
</script>
- Use the uni.getStorageSync(key) method to retrieve the stored user information on the page that requires it.
<template>
<view>
<text>{{ userInfo.username }}</text>
</view>
</template>
<script>
export default {
data() {
return {
userInfo: {},
};
},
onLoad() {
// 获取存储的用户信息
const userInfo = uni.getStorageSync('userInfo');
this.userInfo = userInfo;
},
};
</script>
The code examples above are for demonstration purposes only, and may need to be modified and improved according to specific circumstances in actual application.