Location>code7788 >text

How to achieve unified management of four global state data in Vue3?

Popularity:525 ℃/2024-10-10 19:58:45

Four types of global state data

There are four types of global state data that are encountered in actual development:Asynchronous data (generally from the server side)Synchronized data. Synchronized data is subdivided into three types:localstoragecookierandom access memory (RAM)In traditional Vue3, different mechanisms are used to handle this state data. In traditional Vue3, different mechanisms are used to handle this state data, whereas in Zova it's just a matter of using the unifiedModelmachine

status data Traditional Vue3 Zova
asynchronous data Pinia Model
localstorage Pinia + Localstorage Model
cookie Pinia + Cookie Model
random access memory (RAM) Pinia Model

Adopting a Model mechanism to unify the management of this global state data provides a number of generalized system capabilities, such as.Memory Optimizationobjectificationcap (a poem)SSR supportand so on, so as to standardize the use of data, simplify the structure of the code, improve the maintainability of the code

Feature 1: Support for asynchronous and synchronous data

The base of the Zova Model isTanStack QueryTanStack Query provides powerful data fetching, caching and updating capabilities. If you haven't used a data management mechanism like TanStack Query, it's highly recommended to learn about it, and I'm sure you'll be baptized with ideas!
However, the core of TanStack Query is the management of asynchronous data (typically from the server side.) Zova Model extends TanStack Query so that it also supports the management of synchronous data. In other words, all of the features and capabilities described below apply to both theasynchronous datacap (a poem)Synchronized data

Feature 2. Automatic caching

Asynchronous data is cached locally to avoid duplicate fetches. For synchronized data, it will automatically read and write against localstorage or cookies.

Feature 3: Automatic updating

Provide data expiration policies to automatically update at the right time

Feature 4: Reduction of duplicate requests

When data is accessed from multiple places in the application at the same time, the server-side api will be called only once, and in the case of synchronized data, the operation will be called only once for localstorage or cookies.

Feature 5. Memory optimization

The data managed by Zova Model, although it is a globally scoped state, does not always occupy memory, but provides a mechanism for memory release and reclamation. Specifically, the cached data is created according to the business needs when creating Vue component instances, and when the Vue component instances are uninstalled, the references to the cached data are released, and if there are still no references to the cached data by other Vue components when the agreed expiration time is reached, the reclaiming mechanism (GC) will be triggered to complete the release of the memory, thus saving the memory usage. This is a significant benefit for large projects where users need to interact with the interface for a long time.

Attribute 6: Persistence

The local cache can be persisted and automatically restored when the page is refreshed to avoid server-side calls. If the data is asynchronous, it will be automatically persisted to IndexDB, so as to meet the storage needs of large amount of data. If the data is synchronous, it will be automatically persisted to localstorage or cookie.

Memory Optimizationtogether withobjectificationThe effect is more obvious for large projects. For example, the first time data is fetched from the server, a local cache is generated and automatically persisted. When the page is no longer in use and expires, the local cache is automatically destroyed, freeing up memory. When the data is accessed again, the local cache is automatically restored from the persistence instead of fetching the data from the server again.

Feature 7.

Different types of state data also have different implementation mechanisms in the SSR model. zova Model smoothes out these state data differences and hydrates them with a unified mechanism, which makes SSR implementation more natural and intuitive, and significantly reduces the mental burden.

Feature 8. Automatic namespace isolation

Zova manages data through Model Bean. The bean itself has a unique identifier that can be used as a namespace for data, which automatically ensures the uniqueness of state data naming inside the bean and avoids data conflicts.

  • See also:Bean identifier

How to create a Model Bean

Zova provides a VS Code plugin that makes it easy to create a Model Bean via the right-click menu.

Context menu - [module path]: [module path]: [module path]: [module path]: [module path].Zova Create/Bean: Model

Enter the name of the model bean when prompted, for exampletodoThe VSCode plugin automatically adds the code skeleton of the model bean.

For example, to create a Model Bean in the demo-todo moduletodo

demo-todo/src/bean/

import { Model } from 'zova';
import { BeanModelBase } from 'zova-module-a-model';

@Model()
export class ModelTodo extends BeanModelBase {}
  • Using the @Model Decorator
  • Inherited from base class BeanModelBase

asynchronous data

The core of TanStack Query is the management of server-side data. For the sake of simplicity, we will only show the definition and use of the select method here.

  • For a full code example, see:demo-todo

How to define

@Model()
export class ModelTodo {
  select() {
    return this.$useQueryExisting({
      queryKey: ['select'],
      queryFn: async () => {
        return ();
      },
    });
  }
}
  • Call $useQueryExisting to create a Query object.
    • Why not use$useQuerymethod? This is because asynchronous data is generally loaded asynchronously only when it is needed. So we need to make sure that we are calling theselectmethod always returns the same Query object, so you must use the$useQueryExistingmethodologies
  • Pass in a queryKey to ensure uniqueness of the local cache
  • Pass in queryFn and call this function at the right time to get the server-side data.
    • : seeApi Services

How to use

demo-todo/src/page/todo/

import { ModelTodo } from '../../bean/';

export class ControllerPageTodo {
  @Use()
  $$modelTodo: ModelTodo;
}
  • Inject Model Bean instance: $$modelTodo

demo-todo/src/page/todo/

export class RenderTodo {
  render() {
    const todos = this.$$();
    return (
      <div>
        <div>isLoading: {}</div>
        <div>
          {?.map(item => {
            return <div>{}</div>;
          })}
        </div>
      </div>
    );
  }
}
  • Call the select method to get the Query object
    • The render method is executed multiple times, and repeated calls to the select method return the same Query object.
  • Using state and data directly from Query objects
    • See also:TanStack Query: Queries

How to support SSR

In SSR mode, we need to use asynchronous data in this way: state data is loaded on the server side, and then rendered into an html string by the render method. The state data and the html string are sent to the client at the same time, and the client still uses this same state data when performing the hydration, thus maintaining state consistency.

To implement the above logic, there is only one step to perform in Zova Model:

demo-todo/src/page/todo/

import { ModelTodo } from '../../bean/';

export class ControllerPageTodo {
  @Use()
  $$modelTodo: ModelTodo;

  protected async __init__() {
    const queryTodos = this.$$();
    await ();
    if () throw ;
  }
}
  • Simply add the__init__method of thesuspenseWait for asynchronous data loading to complete

Synchronized data: localstorage

Since the server side does not supportTherefore, localstorage status data are not involved in the hydration process of SSRs.

The following demonstrates storing user information in localstorage, which also maintains the state when the page is refreshed

How to define

export class ModelUser extends BeanModelBase {
  user?: ServiceUserEntity;

  protected async __init__() {
     = this.$useQueryLocal({
      queryKey: ['user'],
    });
  }
}
  • together withasynchronous dataUnlike the definitions, the synchronization data is directly defined in the initialization method__init__Medium Definition
  • Call $useQueryLocal to create a Query object.
  • Pass in a queryKey to ensure the uniqueness of the local cache

How to use

Read and set data directly like regular variables

const user = ;
 = newUser;

Synchronized data: cookie

On the server side it will automatically use theRequest HeaderCookies are automatically used on the client's side in theThis automatically ensures the consistency of cookie state data during SSR hydration.

The following demonstrates storing a user token into a cookie, which also maintains its state when the page is refreshed. This way, in SSR mode, both the client and the server can use the samejwt tokenAccess to back-end API services

How to define

export class ModelUser extends BeanModelBase {
  token?: string;

  protected async __init__() {
     = this.$useQueryCookie({
      queryKey: ['token'],
    });
  }
}
  • together withasynchronous dataUnlike the definitions, the synchronization data is directly defined in the initialization method__init__Medium Definition
  • Call $useQueryCookie to create a Query object.
  • Pass in a queryKey to ensure the uniqueness of the local cache

How to use

Read and set data directly like regular variables

const token = ;
 = newToken;

Synchronized data: Memory

In SSR mode, the global state data defined on the server side is synchronized to the client side and the hydration is done automatically

The following demonstrates memory-based global state data

How to define

zova-ui-quasar/src/suite-vendor/a-quasar/modules/quasar-adapter/src/bean/

export class ModelTheme extends BeanModelBase {
  cBrand: string;

  protected async __init__() {
     = this.$useQueryMem({
      queryKey: ['cBrand'],
    });
  }
}
  • together withasynchronous dataUnlike the definition, the synchronization data is directly defined in the initialization method__init__Medium Definition
  • Call $useQueryMem to create a Query object.
  • Pass in a queryKey to ensure the uniqueness of the local cache

How to use

Read and set data directly like regular variables

const cBrand = ;
 = newValue;

concluding remarks

Zova is a Vue3 framework that supports IOC containers, combining the best of Vue/React/Angular while avoiding their shortcomings to make our development experience more elegant and less taxing on the mind.Zova has a lot of useful and interesting features built in, and the Model mechanism is just one of them.

Zova framework has been open source, welcome to pay attention to, participate in the co-construction:/cabloy/zovaThe following is a list of the most important things you can do for your business. You can add my WeChat, into the group exchange: yangjian2025