ui-ts-local-storage.md 12.4 KB
Newer Older
E
ester.zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# LocalStorage

> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.

**LocalStorage** is a storage unit in an application. Its lifecycle is determined by the ability to which it is bound. **LocalStorage** provides storage for variable and non-variable state attributes within the scope of an application. The variable and non-variable state attributes work together to build an application UI, including the UI of abilities.

Application layer: Multiple **LocalStorage** instances can be created for an application. Each ability of an application corresponds to a **LocalStorage** instance.

Ability: An application can have multiple abilities. Only one **LocalStorage** instance can be allocated to the child components of an ability. Once allocated a **LocalStorage** instance, the child components have access to objects stored in the **LocalStorage**.

A component can access only one **LocalStorage** instance, and a **LocalStorage** instance can be allocated to multiple components.

## @LocalStorageLink Decorator

E
ester.zhou 已提交
17
Two-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageLink** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. If no initial value is assigned in the **LocalStorage**, the state variable will use the value defined by **@LocalStorageLink**. Changes made to this variable in the component will be first synchronized to the **LocalStorage**, and then to other components of the bound ability.
E
ester.zhou 已提交
18 19 20

## @LocalStorageProp Decorator

E
ester.zhou 已提交
21
One-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageProp** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. Changes made to the value in the **LocalStorage** will cause all UI components of the bound ability to update the state.
E
ester.zhou 已提交
22 23 24

> **NOTE**
>
E
ester.zhou 已提交
25
> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead.
E
ester.zhou 已提交
26

E
ester.zhou 已提交
27
## LocalStorage
E
ester.zhou 已提交
28 29 30 31 32 33 34 35 36

### constructor  

constructor(initializingProperties?: Object)

Creates and initializes a **LocalStorage** instance.

**Parameters**

E
ester.zhou 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| Name                   | Type    |  Mandatory | Default Value | Description                                    |
| ---------------------- | ------ | :--: | ---- | ---------------------------------------- |
| initializingProperties | Object |  No  | -    | Object attributes and their values returned by **object.keys(obj)**.|



### GetShared

static GetShared(): LocalStorage

Obtains the current shared **LocalStorage** object.

This API can be used only in the stage model.

**Return value**

| Type                           | Description               |
| ----------------------------- | ----------------- |
| [LocalStorage](#localstorage) | **LocalStorage** object.|
E
ester.zhou 已提交
56 57 58 59 60 61 62 63 64 65 66



### has

has(propName: string): boolean

Checks whether the **LocalStorage** contains the specified attribute value.

**Parameters**

E
ester.zhou 已提交
67 68 69
| Name     | Type    |  Mandatory | Default Value | Description   |
| -------- | ------ | :--: | ---- | ------- |
| propName | string |  Yes  | -    | Attribute value.|
E
ester.zhou 已提交
70 71 72

**Return value**

E
ester.zhou 已提交
73 74
| Type     | Description           |
| ------- | ------------- |
E
ester.zhou 已提交
75 76 77 78 79 80 81 82 83 84 85 86
| boolean | Whether the attribute value is contained.|



### get

get\<T>(propName: string): T

Obtains the value corresponding to the given key.

**Parameters**

E
ester.zhou 已提交
87 88 89
| Name     | Type    |  Mandatory | Default Value | Description       |
| -------- | ------ | :--: | ---- | ----------- |
| propName | string |  Yes  | -    | Key of the value to obtain.|
E
ester.zhou 已提交
90 91 92

**Return value**

E
ester.zhou 已提交
93 94
| Type            | Description                                      |
| -------------- | ---------------------------------------- |
E
ester.zhou 已提交
95 96 97 98 99 100 101 102 103 104 105 106
| T \| undefined | Returns the value if it is found; returns **undefined** otherwise.|



### set

set\<T>(propName: string, newValue: T): boolean

Sets the value for the given key.

**Parameters**

E
ester.zhou 已提交
107 108 109 110
| Name     | Type    |  Mandatory | Default Value | Description       |
| -------- | ------ | :--: | ---- | ----------- |
| propName | string |  Yes  | -    | Key of the value to set.  |
| newValue | T      |  Yes  | -    | Value to set.|
E
ester.zhou 已提交
111 112 113

**Return value**

E
ester.zhou 已提交
114 115
| Type     | Description                                 |
| ------- | ----------------------------------- |
E
ester.zhou 已提交
116 117 118 119 120 121 122 123 124 125 126 127
| boolean | Returns **true** if the value is successfully set for the key; returns **false** otherwise.|



### setOrCreate

setOrCreate\<T>(propName: string, newValue: T): boolean

Creates or updates the value for the given key.

**Parameters**

E
ester.zhou 已提交
128 129 130 131
| Name     | Type    |  Mandatory | Default Value | Description          |
| -------- | ------ | :--: | ---- | -------------- |
| propName | string |  Yes  | -    | Key of the value to create or update. |
| newValue | T      |  Yes  | -    | Value to create or update.|
E
ester.zhou 已提交
132 133 134

**Return value**

E
ester.zhou 已提交
135 136 137
| Type     | Description                                      |
| ------- | ---------------------------------------- |
| boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value of the T type as its default value and returns **false** otherwise. **true** cannot be returned for **undefined** or **null**.|
E
ester.zhou 已提交
138 139 140 141 142 143 144 145 146 147 148



### link

link\<T>(propName: string): T

Establishes two-way data binding between an attribute and this **LocalStorage** instance.

**Parameters**

E
ester.zhou 已提交
149 150 151
| Name     | Type    |  Mandatory | Default Value | Description       |
| -------- | ------ | :--: | ---- | ----------- |
| propName | string |  Yes  | -    | Key of the target attribute.|
E
ester.zhou 已提交
152 153 154

**Return value**

E
ester.zhou 已提交
155 156
| Type  | Description                                      |
| ---- | ---------------------------------------- |
E
ester.zhou 已提交
157 158 159 160 161 162 163 164
| T    | Returns the two-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise.|



### setAndLink

setAndLink\<T>(propName: string, defaultValue: T): T

E
ester.zhou 已提交
165
Establishes two-way data binding between an attribute and this **LocalStorage** instance. This API works in a way similar to the **link** API.
E
ester.zhou 已提交
166 167 168

**Parameters**

E
ester.zhou 已提交
169 170 171 172
| Name         | Type    |  Mandatory | Default Value | Description       |
| ------------ | ------ | :--: | ---- | ----------- |
| propName     | string |  Yes  | -    | Key of the target attribute.|
| defaultValue | T      |  Yes  | -    | Default value to set. |
E
ester.zhou 已提交
173 174 175

**Return value**

E
ester.zhou 已提交
176 177 178
| Type                                | Description                                                        |
| ------------------------------------ | ------------------------------------------------------------ |
| [@Link](ts-component-states-link.md) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Link** instance with the specified value as its default value otherwise.|
E
ester.zhou 已提交
179 180 181 182 183 184 185 186 187 188 189



### prop

prop\<T>(propName: string): T

Establishes one-way data binding with an attribute to update its status.

**Parameters**

E
ester.zhou 已提交
190 191 192
| Name     | Type    |  Mandatory | Default Value | Description         |
| -------- | ------ | :--: | ---- | ------------- |
| propName | string |  Yes  | -    | Key of the target attribute.|
E
ester.zhou 已提交
193 194 195

**Return value**

E
ester.zhou 已提交
196 197
| Type                                  | Description                                      |
| ------------------------------------ | ---------------------------------------- |
E
ester.zhou 已提交
198
| [@Prop](ts-component-states-prop.md) | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. This means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will not be synchronized to the **LocalStorage**. Note that the variables returned are immutable variables, which are applicable to mutable and immutable state variables. |
E
ester.zhou 已提交
199 200 201 202 203 204 205



### setAndProp

setAndProp\<T>(propName: string, defaultValue: T): T

E
ester.zhou 已提交
206
Sets up one-way data binding with the **localStorage**. This API works in a way similar to the **Prop** API.
E
ester.zhou 已提交
207 208 209

**Parameters**

E
ester.zhou 已提交
210 211 212 213
| Name         | Type    |  Mandatory | Default Value | Description           |
| ------------ | ------ | :--: | ---- | --------------- |
| propName     | string |  Yes  | -    | Key value in the key-value pair to be saved.|
| defaultValue | T      |  Yes  | -    | Default value to set.        |
E
ester.zhou 已提交
214 215 216

**Return value**

E
ester.zhou 已提交
217 218 219
| Type                                  | Description                                      |
| ------------------------------------ | ---------------------------------------- |
| [@Prop](ts-component-states-prop.md) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Prop** instance with the specified value as its default value otherwise.|
E
ester.zhou 已提交
220 221 222 223 224 225 226 227 228 229 230



### delete

delete(propName: string): boolean

Deletes the key-value pair specified by key.

**Parameters**

E
ester.zhou 已提交
231 232 233
| Name     | Type    |  Mandatory | Default Value | Description        |
| -------- | ------ | :--: | ---- | ------------ |
| propName | string |  Yes  | -    | Key value of the attribute to be deleted.|
E
ester.zhou 已提交
234 235 236

**Return value**

E
ester.zhou 已提交
237 238 239
| Type     | Description                                      |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.|
E
ester.zhou 已提交
240 241 242 243 244 245 246 247 248 249 250



### keys

keys(): IterableIterator\<string>

Searches for all keys.

**Return value**

E
ester.zhou 已提交
251 252
| Type            | Description            |
| -------------- | -------------- |
E
ester.zhou 已提交
253 254 255 256 257 258 259 260 261 262 263 264
| array\<string> | Returns an array of strings containing all keys.|



### size

size(): number

Number of existing key-value pairs.

**Return value**

E
ester.zhou 已提交
265 266
| Type    | Description       |
| ------ | --------- |
E
ester.zhou 已提交
267 268 269 270 271 272 273 274 275 276 277 278
| number | Number of key-value pairs.|



### Clear

clear(): boolean

Deletes all attributes.

**Return value**

E
ester.zhou 已提交
279 280 281
| Type     | Description                               |
| ------- | --------------------------------- |
| boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
E
ester.zhou 已提交
282 283 284

### Example 1 (Creating a LocalStorage in an Ability)

E
ester.zhou 已提交
285 286
```ts
import Ability from '@ohos.application.Ability'
E
ester.zhou 已提交
287 288
export default class MainAbility extends Ability {    
  storage : LocalStorage    
E
ester.zhou 已提交
289
  onCreate() {    
E
ester.zhou 已提交
290 291
    this.storage = new LocalStorage();
    this.storage.setOrCreate("storageSimpleProp",121);    
E
ester.zhou 已提交
292
    console.log("[Demo MainAbility onCreate]"); 
E
ester.zhou 已提交
293 294 295 296 297
  }  
  onDestroy() {    
    console.log("[Demo MainAbility onDestroy]")  
  }    
  onWindowStageCreate(windowStage) {
E
ester.zhou 已提交
298
    windowStage.loadContent("pages/index",this.storage)    
E
ester.zhou 已提交
299 300
  }    
  onWindowStageDestroy() {
E
ester.zhou 已提交
301
    console.log("[Demo] MainAbility onWindoeStageDestroy") 
E
ester.zhou 已提交
302 303 304 305 306 307 308 309 310 311 312 313
  }    
  onForeground() {
    console.log("[Demo] MainAbility onForeground")   
  }    
  onBackground() {
    console.log("[Demo] MainAbility onBackground")    
  }
}
```

The @Component decorated component obtains data.

E
ester.zhou 已提交
314
```ts
E
ester.zhou 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
let storage = LocalStorage.GetShared()
@Entry(storage)
@Component
struct LocalStorageComponent {
  @LocalStorageLink("storageSimpleProp") simpleVarName: number = 0
  build() {
    Column(){
      Text(this.simpleVarName.toString())
        .onClick(()=>{
          this.simpleVarName +=1;
        })
      Text(JSON.stringify(this.simpleVarName))
        .fontSize(50)
    }
    .height(500)
  }
}
```

### Example 2 (Defining LocalStorage on the Entry Page)

E
ester.zhou 已提交
336
```ts
E
ester.zhou 已提交
337 338 339 340
let storage = new LocalStorage({"PropA":47});
@Entry(storage)
@Component 
struct ComA {    
E
ester.zhou 已提交
341
  @LocalStorageLink("PropA") storLink: number = 1;    
E
ester.zhou 已提交
342 343
  build() {    
	Column() {        
E
ester.zhou 已提交
344
	  Text(`Parent from LocalStorage ${ this.storLink }`)            				     
E
ester.zhou 已提交
345
        .onClick(()=>this.storLink+=1)            
E
ester.zhou 已提交
346 347
	  Child()    
 	}    
E
ester.zhou 已提交
348 349 350 351 352 353
  }
}


@Component
struct Child{    
E
ester.zhou 已提交
354
  @LocalStorageLink("PropA") storLink: number = 1;    
E
ester.zhou 已提交
355
  build() {    
E
ester.zhou 已提交
356 357
	Text(`Parent from LocalStorage ${ this.storLink }`)        
	  .onClick(()=>this.storLink+=1)    
E
ester.zhou 已提交
358 359 360
  }
}
```