Home WeChat Applet Mini Program Development Analysis of cache in WeChat applet

Analysis of cache in WeChat applet

Jun 23, 2018 pm 02:41 PM
WeChat applet cache

This article mainly introduces the relevant information of WeChat Mini Program cache (local cache, asynchronous cache, synchronous cache). Friends in need can refer to

WeChat Mini Program Cache

About local cache

1.wx.setStorage(wx.setStorageSync)、wx.getStorage(wx.getStorageSync)、wx.clearStorage(wx.clearStorageSync)

You can set, get and clean the local cache. The maximum local cache is 10MB

2.localStorage is permanent storage

1. Asynchronous cache

wx. setStorage(OBJECT)

Store the data in the specified key in the local cache, and will overwrite the original content corresponding to the key

wx.setStorage({

 key:"key",

 data:"value"

})
Copy after login

wx.getStorage(OBJECT)

Asynchronously obtain the content corresponding to the specified key from the local cache.

wx.getStorage({

 key: 'key',

 success: function(res) {

   console.log(res.data)

 }

})
Copy after login

wx.getStorageInfo(OBJECT)

Asynchronously obtain relevant information about the current storage

wx.getStorageInfo({

 success: function(res) {

  console.log(res.keys)

  console.log(res.currentSize)

  console.log(res.limitSize)

 }

})
Copy after login

wx.removeStorage(OBJECT)

Asynchronously remove the specified key from the local cache.

wx.removeStorage({

 key: 'key',

 success: function(res) {

  console.log(res.data)

 }

})
Copy after login

2. Synchronization cache

wx.setStorageSync(KEY,DATA)

Storing data in the specified key in the local cache will overwrite the original content corresponding to the key. This is a synchronization interface.

wx.getStorageSync(KEY)

Synchronously obtain the content corresponding to the specified key from the local cache.

wx.getStorageInfoSync

Synchronously obtain relevant information about the current storage

wx.removeStorageSync(KEY)

Synchronically remove the specified key from the local cache.

3. Clear the cache

wx.clearStorage()

Clear the local data cache.

wx.clearStorageSync()

Synchronically clear the local data cache

About the difference between synchronous cache and asynchronous cache

Everything ending with Sync (synchronous, simultaneously) is a synchronous cache. The difference between the two is that asynchronous will not block the current task, and the synchronous cache cannot continue until the synchronization method is processed. implement.

But generally do not clear all caches. If you want to clear the corresponding cache, just set the corresponding cache content to an empty array

About historical search

<input type="text" class="search-icon" placeholder="请输入要搜索的内容" bindinput="searchNameInput"/>
<text bindtap="setSearchStorage">搜索</text>


<view>
  <view>
    <text style="float:left;" bindtap="deleteHistory">历史搜索</text>
    <text style="float:right;" bindtap="deleteHistory">删除搜索历史</text>
  </view>
  <view>
    <view class="search-list" wx:for="{{searchData}}" wx:key="item">
      <view>{{item == null?&#39;暂无数据&#39;:item}}</view>
    </view>
  </view>
</view>
Copy after login

Page

There are three binding events here

bindinput=" searchNameInput" Get the data entered by the user

bindtap="setSearchStorage" Set local storage

##bindtap="deleteHistory" Delete historical search

 //获取用户输入框的值
  searchNameInput:function(e){
    var that = this;
    that.setData({
      inputValue:e.detail.value
    })
  }

e.detail.value就代表了当前输入值
Copy after login

When you click search, bindtap="setSearchStorage"

//将用户输入的内容存入本地缓存,并且将搜索数据放到首页
setSearchStorage:function(){
  var that = this
  if(this.data.inputValue != &#39;&#39;){
    //调用API向本地缓存存入数据
    var searchData = wx.getStorageSync(&#39;searchData&#39;) || [] 
    searchData.push(this.data.inputValue) 
    wx.setStorageSync(&#39;searchData&#39;, searchData)

    //读取用户搜索商品
    var name = this.data.inputValue
    wx.request({
     url: &#39;www.shop.com/home/product/search&#39;,
     data: {name:name},
     method: &#39;GET&#39;, 
     success: function(res){
        that.setData({
        goodsList: res.data.info,
      })
     },
    })
  }
}
Copy after login

Process This goes like this:

1. The user enters data and clicks search

2. If the data is not empty, add (set) the local cache

3. Go to the server to search for what the user wants Assign the required data to the variable on this page

4. Click Delete to remove the local value of this key

The cached form here is key=>value

var searchData = wx.getStorageSync('searchData') || []

Get the local cache named 'searchData'. If the cache 'searchData' does not exist, it is equivalent to recreating it. Empty array, assigned to the searchData variable

searchData.push(this.data.inputValue)

PUSH the value entered by the user into the searchData variable

wx.setStorageSync('searchData', searchData)

Call the API interface and reset the cached value of key = 'searchData' to equal searchData

The following The wx.request is the content of the requested data. I'm tired of talking about it, but it's impressive enough.

There is no bindtap to get the cache, just get it and add it to the data in the Page

//从本地获取历史搜索数据

     var searchData = wx.getStorageSync(&#39;searchData&#39;)||[]

      this.setData({

        searchData:searchData

      })

 

deleteHistory

//删除历史搜索数据

  deleteHistory:function(){

    var that = this

    wx.showModal({

    title: &#39;提示&#39;,

    content: &#39;是否删除历史搜索&#39;,

    success: function(res) {

      if (res.confirm) {

        wx.setStorageSync(&#39;searchData&#39;, []);

        wx.switchTab({

          url: &#39;/pages/index/index&#39;,

        })

       }

      }

    })

}
Copy after login

Here is the 'searchData 'The cached value of this key is an empty array, instead of using wx.clearStorageSync provided by the API. This will clear all other caches, and I just want to clear the cache of this key.

The above is the entire article Content, I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

WeChat Mini Program Pop-up window customization code

Implementation of message prompt box of WeChat applet

The above is the detailed content of Analysis of cache in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are video files stored in browser cache? Where are video files stored in browser cache? Feb 19, 2024 pm 05:09 PM

Which folder does the browser cache the video in? When we use the Internet browser every day, we often watch various online videos, such as watching music videos on YouTube or watching movies on Netflix. These videos will be cached by the browser during the loading process so that they can be loaded quickly when played again in the future. So the question is, in which folder are these cached videos actually stored? Different browsers store cached video folders in different locations. Below we will introduce several common browsers and their

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

How to view and refresh dns cache in Linux How to view and refresh dns cache in Linux Mar 07, 2024 am 08:43 AM

DNS (DomainNameSystem) is a system used on the Internet to convert domain names into corresponding IP addresses. In Linux systems, DNS caching is a mechanism that stores the mapping relationship between domain names and IP addresses locally, which can increase the speed of domain name resolution and reduce the burden on the DNS server. DNS caching allows the system to quickly retrieve the IP address when subsequently accessing the same domain name without having to issue a query request to the DNS server each time, thereby improving network performance and efficiency. This article will discuss with you how to view and refresh the DNS cache on Linux, as well as related details and sample code. Importance of DNS Caching In Linux systems, DNS caching plays a key role. its existence

Speed ​​up your applications: A simple guide to Guava caching Speed ​​up your applications: A simple guide to Guava caching Jan 31, 2024 pm 09:11 PM

A Beginner's Guide to Guava Cache: Speed ​​Up Your Applications Guava Cache is a high-performance in-memory caching library that can significantly improve application performance. It provides a variety of caching strategies, including LRU (least recently used), LFU (least recently used), and TTL (time to live). 1. Install Guava cache and add the dependency of Guava cache library to your project. com.goog

Will HTML files be cached? Will HTML files be cached? Feb 19, 2024 pm 01:51 PM

Title: Caching mechanism and code examples of HTML files Introduction: When writing web pages, we often encounter browser cache problems. This article will introduce the caching mechanism of HTML files in detail and provide some specific code examples to help readers better understand and apply this mechanism. 1. Browser caching principle In the browser, whenever a web page is accessed, the browser will first check whether there is a copy of the web page in the cache. If there is, the web page content is obtained directly from the cache. This is the basic principle of browser caching. Benefits of browser caching mechanism

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Advanced Usage of PHP APCu: Unlocking the Hidden Power Advanced Usage of PHP APCu: Unlocking the Hidden Power Mar 01, 2024 pm 09:10 PM

PHPAPCu (replacement of php cache) is an opcode cache and data cache module that accelerates PHP applications. Understanding its advanced features is crucial to utilizing its full potential. 1. Batch operation: APCu provides a batch operation method that can process a large number of key-value pairs at the same time. This is useful for large-scale cache clearing or updates. //Get cache keys in batches $values=apcu_fetch(["key1","key2","key3"]); //Clear cache keys in batches apcu_delete(["key1","key2","key3"]);2 .Set cache expiration time: APCu allows you to set an expiration time for cache items so that they automatically expire after a specified time.

The relationship between CPU, memory and cache is explained in detail! The relationship between CPU, memory and cache is explained in detail! Mar 07, 2024 am 08:30 AM

There is a close interaction between the CPU (central processing unit), memory (random access memory), and cache, which together form a critical component of a computer system. The coordination between them ensures the normal operation and efficient performance of the computer. As the brain of the computer, the CPU is responsible for executing various instructions and data processing; the memory is used to temporarily store data and programs, providing fast read and write access speeds; and the cache plays a buffering role, speeding up data access speed and improving The computer's CPU is the core component of the computer and is responsible for executing various instructions, arithmetic operations, and logical operations. It is called the "brain" of the computer and plays an important role in processing data and performing tasks. Memory is an important storage device in a computer.

See all articles