当前位置:网站首页>Wechat applet realizes store function
Wechat applet realizes store function
2022-06-29 09:52:00 【milugloomy】
Start
Last issue 《 Wechat applet implements data listener watch》, In the small program to achieve Vue Of watch function . But applets don't have state management , In the current situation , Cross page communication and data transmission are very painful , It will be difficult to maintain and debug . Let's do it this time store, Global state management function , To solve the problem of egg pain , There are several goals :
- stay Page and Component Can be used in all lifecycles and functions in store, Can be modified state
- A few lines of code will introduce , Do not modify the previous code structure , You don't need to introduce... On every page
- Usage and vue equally
programme
store It's actually a global variable , All pages share , Realization store Functions include 2 A key point
- Page and Component How to reference global variables in state, How to render data to a page
- Changed global variables state, How to put other Page and Component Global variables referenced state Also update and render to the page
The first question is , stay Page Of onLoad Functions and Component Of attached In the function , stay options Add a pair of global variables in state References to , And call this.setData Method will change the variable state The data is rendered to the page
The second question is , Need to maintain a list , The currently loaded Page and Component All stored , That is to say Page Of onLoad Functions and Component Of attached Function to add the current object to the list , stay Page Of onUnload Functions and Component Of detached Function to remove the current object from the list . Then when there is a call setState When the method is used , Traverse all the objects in this list , call this.setData Method will change the variable state The data is rendered to the page .
Let's look at the implementation code , Write a store.js, The contents are as follows :
// Global variables
let store = {
msg: 'xxxxx',
user: {}
}
// All loaded pages and components
let pcList = []
function initPage() {
let oldPage = Page
Page = function(obj) {
let oldOnLoad = obj.onLoad || function() {}
let oldOnUnload = obj.onUnload || function() {}
obj.onLoad = function() {
// Realization store function ,onLoad Will be state Add to Page Of data in
loadStore.call(this)
// Realization store Of setState function
this.setState = function(obj) {
setState.call(this, obj)
}
oldOnLoad.call(this, ...arguments)
}
obj.onUnload = function() {
// hold this Spread function
unloadStore.call(this)
oldOnUnload.call(this, ...arguments)
}
return oldPage(obj)
}
}
function initComponent() {
let oldComponent = Component
Component = function(obj) {
let oldAttached = obj.attached || function() {}
let oldDetached = obj.detached || function() {}
obj.attached = function() {
// Realization store function ,onLoad Will be state Add to Component Of data in
loadStore.call(this)
// Realization store Of setState function
this.setState = function(obj) {
setState.call(this, obj)
}
oldAttached.call(this, ...arguments)
}
obj.detached = function() {
// hold this Spread function
unloadStore.call(this)
oldDetached.call(this, ...arguments)
}
return oldComponent(obj)
}
}
function setState(obj) {
let keys = Object.keys(obj)
let newObj = {}
keys.forEach(key => {
newObj['$state.' + key] = obj[key]
})
// Update all components and pages
pcList.forEach(item => {
item.setData(newObj)
})
}
function loadStore() {
// Join in pcList, stay setState Traversing when you need to
pcList.push(this)
// Every page or component is in data Store one copy in state References to
this.$state = store
this.setData({
$state: store
})
}
function unloadStore() {
// from pcList Remove
let index = pcList.findIndex(item => {
return item === this
})
if (index > -1) {
pcList.splice(index, 1)
}
}
initPage()
initComponent()
Use
The first is introduction , stay app.js introduce store.js that will do
import './utils/store.js'Then use the method , stay wxml Use in
<view>{
{$state.msg}}</view>stay js In order to get state And update state
Page({
//...
func(){
// obtain state Medium user
let storeUser = this.$state.user
storeUser.name = 'Becky'
// to update state Medium user
this.setState({
user:storeUser
})
}
})Conclusion
We did store function , And achieved the three goals written at the beginning , Can be used in all lifecycles and functions , One line of code can introduce , Usage and Vue equally .
But only the most basic store function , But it can meet the needs of the current project , If there are other needs in the future , On this basis, add .
边栏推荐
- 数据治理:数据治理在数据中台下的解决方案
- Chang'an chain go language smart contract writing and compilation
- Visual assist plug-in settings for UE4 vs
- Closed door cultivation (24) shallow understanding of cross domain problems
- General part: cognition, design and best practice of prototype design
- Official STM32 chip package download address stm32f10x stm32f40x Download
- Uber 前安全主管面临欺诈指控,曾隐瞒数据泄露事件
- programing language
- 自定义mvc框架实现
- 数据治理:数据标准管理(第三篇)
猜你喜欢

如何将谷歌浏览器设置为默认浏览器

Mysql配置主从数据库
![[Huawei certification] the most complete and selected question bank in hcia-datacom history (with answer analysis)](/img/d4/f5ea847573433f7ca7bd429f57e40a.png)
[Huawei certification] the most complete and selected question bank in hcia-datacom history (with answer analysis)

The principle of session and cookie

Do you know what BFD is? This article explains the principle and usage scenarios of BFD protocol in detail

The former security director of Uber faced fraud allegations and concealed the data leakage event

五心公益红红娘团队

Segmentation of Head and Neck Tumours Using Modified U-net

Segmentation of Head and Neck Tumours Using Modified U-net

商业智能BI的未来,如何看待AI+BI这种模式?
随机推荐
Es error nonodeavailableexception[none of the configured nodes are available:[.127.0.0.1}{127.0.0.1:9300]
Five heart charity matchmaker team
你知道BFD是什么吗?一文详解BFD协议原理及使用场景
watch监听和computed计算属性的使用和区别
我想要股票开户优惠,怎么得到?还有,在线开户安全么?
How to implement observer mode
数据可视化:数据可视化的意义
第十二章 信号(二)- 生产者消费者示例
Gd32f4xx Ethernet Chip (ENC28J60) Drive transplantation
装饰器模式的应用,包装ServletRequest,增加addParameter方法
Surveiller l'utilisation du pool de connexion des sources de données
数据治理:元数据管理(第二篇)
Uber 前安全主管面临欺诈指控,曾隐瞒数据泄露事件
UE4 材质UV纹理不随模型缩放拉伸
User level threads and kernel level threads
Fully Automated Delineation of Gross Tumor Volume for Head and Neck Cancer on PET-CT Using Deep Lear
Pytorch Summary - sensor on GPU
linux环境下安装配置redis,并设置开机自启动
A comparison of methods for fully automatic segmentation of tumors and involved nodes in PET/CT of h
Visual assist plug-in settings for UE4 vs