[vue3] Get dictionary data and encapsulate it as a public method

Foreword:

There are basically dictionary management pages in the background project. The main purpose of Vue encapsulating dictionary data is to facilitate data management and use.

No matter on which page the drop-down box is used, the options data source of el-select needs to be obtained by calling the interface. Different data sources call different interfaces, and the introduction and use are not small workload. If you use dictionary data management, no matter the same How many data sources are needed for a page can be done in one method, wouldn't it be much more efficient.

The structure code of the dictionary page is not pasted, as shown in the screenshot.
insert image description here
The list on the left is the dictionary name, and the list on the right is the dictionary label corresponding to the dictionary name and other data

1. Use pinia to access data

Using Pinia to access dictionary data in Vue projects can provide better state management and data sharing mechanisms, simplify component logic and rendering processes, provide type safety and code hints, and expand plug-in and tool support. These advantages make the code clearer, more concise and easier to maintain

Pinia uses a modular approach to divide the state into different modules. This sub-module approach can provide better organization and management, making the state structure clearer and extensible

Create new index.js, and dict.js, index.js under the store folder
insert image description here

const store = createPinia()

export default store

**

Pinia defines the use of the defineStore function to create an independent store small warehouse

The defineStore function receives two parameters,
1. storeName (required): a field string used to define the name of the store

2. storeOptions (optional): an object containing configuration options used to define the store

**
modules–dict.js

const  useDictStore = defineStore('dict',{
state:()=>({
dict:new Array()
}),
actions:{
 // 获取字典
      getDict(_key) {
        if (_key == null && _key == "") {
          return null;
        }
        try {
          for (let i = 0; i < this.dict.length; i++) {
            if (this.dict[i].key == _key) {
              return this.dict[i].value;
            }
          }
        } catch (e) {
          return null;
        }
      },
      // 设置字典
      setDict(_key, value) {
        if (_key !== null && _key !== "") {
          this.dict.push({
            key: _key,
            value: value
          });
        }
      },
      // 删除字典
      removeDict(_key) {
        var bln = false;
        try {
          for (let i = 0; i < this.dict.length; i+

Guess you like

Origin blog.csdn.net/weixin_49668076/article/details/131933027