干货
封装localStorage本地存储方法
在src目录下新建文件夹utils,再新建文件Storage.js。在要使用的页面中引入Storage.js中对应的方法即可。`
Storage.js代码如下:
export const SGet = (key) => {
var value = localStorage.getItem('ruarua' + key)
if (!value || (value == null || value == '' || value == 'null' || value == 'undefined' || value == undefined)) {
localStorage.removeItem('ruarua' + key)
return null;
}
return value;
}
export const SGetByInt = (key) => {
var value = localStorage.getItem('ruarua' + key)
if (!value || (value == null || value == '' || value == 'null' || value == 'undefined' || value == undefined)) {
localStorage.removeItem('ruarua' + key)
return 0;
}
return value;
}
export const SSet = (key, value) => {
if (!value || (value == null || value == '' || value == 'null' || value == 'undefined' || value == undefined)) {
localStorage.removeItem('ruarua' + key)
} else {
localStorage.setItem('ruarua' + key, value)
}
}
export const SRemove = (key) => {
localStorage.removeItem('ruarua' + key)
}
SSet 方法
SSet 方法:上传信息到本地存储。
例如:登录页面上传token
和昵称name
到本地存储,代码如下:
<template>
<div>
<div>账号:<input v-model="user"></div>
<div>密码:<input v-model="pwd"></div>
<div><button @click="login">登录</button></div>
</div>
</template>
<script>
import { getlogin } from '../../axios/testapi';
import { SSet } from "../../utils/Storage";
export default {
data() {
return {
user: null,
pwd: null,
}
},
methods: {
login() {
let _this = this;
getlogin({
'user': this.user,
'pwd': this.pwd
}).then(data => {
if (data.data.errcode == 0) {
SSet('token', data.data.token);
SSet('name', data.data.name);
_this.$toast.success("登录成功");
_this.$router.push('/');
} else {
_this.$toast.fail(data.data.errmsg);
}
})
}
},
name: "login"
}
</script>
SGet 方法
SGet 方法:获取本地存储信息。
例如:获取显示本地存储的昵称name
,代码如下:
<template>
<div>
<div>昵称:{{nick_name}}</div>
</div>
</template>
<script>
import { SGet } from "../../utils/Storage";
export default {
data() {
return {
nick_name: SGet("name")
}
},
name: "index"
}
</script>
SRemove 方法
SRemove 方法:清除本地存储信息。
例如:退出登录时清除本地存储的token
,代码如下:
<template>
<div>
<button @click="outLogin">退出登录</button>
</div>
</template>
<script>
import { SRemove } from "../../utils/Storage";
export default {
methods: {
outLogin() {
SRemove('token');
window.location.reload();
}
},
name: "outLogin"
}
</script>
SGetByInt 方法
SGetByInt 方法:获取本地存储数据,为空时返回 0
。
例如:获取显示本地存储的 获取的状态栏高度immersed
,代码如下:
<template>
<div>
<van-sticky :offset-top="mtop">
<van-nav-bar title="标题"/>
</van-sticky>
<div>内容</div>
</div>
</template>
<script>
import { SRemove } from "../../utils/Storage";
export default {
data() {
return {
mtop: SGetByInt('immersed')
}
},
name: "index2"
}
</script>