当前位置:   article > 正文

uniapp 实现本地存储读取_uniapp中存储的数组这么读出来

uniapp中存储的数组这么读出来

要求

1、实现搜索框输入内容按下搜索按钮或回车后,将搜索框的内容存入本地,

2、以搜索历史记录的形式读取本地数据

3、添加一个清空历史记录的功能

html部分

  1. <view>
  2. <view class="x">
  3. <u-search style=" border-radius: 20px;" placeholder="输入小区/商圈/地铁站等" actionText='' searchIcon=''
  4. @search="Storage" v-model="setval"></u-search>
  5. <view class="show">
  6. <text style="color: #787C7D;">搜索历史</text>
  7. <u-icon @click="historeDelete" name="trash" size="30" ></u-icon>
  8. </view>
  9. <view style="display: flex; margin-top: 30rpx;" v-for="(item,index) in getval" :key="index">
  10. <u-icon name="clock-fill" color="#ccc" size="25"></u-icon>
  11. <text class="tory1">{{item}}</text>
  12. </view>
  13. </view>
  14. </view>
  15. .x{
  16. margin: 50rpx auto;
  17. width: 90%;
  18. height:600rpx;
  19. box-shadow: 0 3px 7px #ccc;
  20. .show{
  21. display: flex;
  22. justify-content: space-between;
  23. padding: 20rpx;
  24. }
  25. .tory1 {
  26. margin-left: 20rpx;
  27. }
  28. }

js部分

  1. data() {
  2. return {
  3. setval: '',
  4. getval: [],
  5. }
  6. },
  7. onLoad() {
  8. uni.getStorageSync('token')
  9. let getval = uni.getStorageSync('token')
  10. console.log('1111', getval); // ['苹果']
  11. if (getval) {
  12. this.getval = JSON.parse(getval)
  13. }
  14. },
  15. methods: {
  16. Storage() {
  17. if (!this.setval) return; // 判断一下输入框是否有内容
  18. let searchval = this.setval
  19. // 使用findindex方法查询一下本地数据中是否有与输入内容重复的
  20. let syncval = this.getval.findIndex(item => item == this.setval)
  21. if(syncval>-1){
  22. this.getval.splice(syncval)
  23. // 此时添加成功了,但是本地中显示为空数组
  24. }
  25. // 所以需要在指定位置添加数据
  26. this.getval.unshift(this.setval)
  27. // 将输入框的数据转化为字符串后存入
  28. uni.setStorageSync('token', JSON.stringify(this.getval))
  29. },
  30. // 清空按钮
  31. historeDelete(){
  32. const that=this
  33. uni.showModal({
  34. title:"温馨提示",
  35. content:"是否确认清空",
  36. success(res){
  37. if(res.confirm){
  38. that.getval=[]
  39. uni.removeStorageSync('token')
  40. }
  41. }
  42. })
  43. }
  44. }
  45. }

效果:

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/758953
推荐阅读