How to use provide to implement state management in Vue3

How to use provide to implement state management in Vue3

Preface

In the Vue ecosystem, Vuex, the official state management library, brings us very convenient functions in Vue application development. However, the size of Vuex 20K+ also brings some costs. For smaller projects, it is not worth introducing Vuex just to store a small amount of data such as user information.

Vue2.2.x later provided the provide/inject API to help us achieve communication between cross-level components.

Vue3.x also puts provide on the application API, which makes it easier for us to implement basic state management on this basis.

How to implement Vuex functions through provide/inject

First, let's think about the general logic, make it into a plug-in, and register it to the application instance through the use method.

In the install method, the data is mounted on the root component through the app.provide method. The data should be responsive data, and for data security, the change of the data should be restricted. It follows the design of unidirectional data flow and cannot be modified directly by users. Therefore, when exposing data, the data should be processed as readonly.

Implement a useStore function similar to Vuex, allowing users to access data through this method.

Implement mapState, mapMutations and mapActions methods similar to Vuex to simplify operations.

The usage is exactly the same as Vuex.

Register this plugin in your application

//main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

import store from './store'

const app = createApp(App)

app.use(router).use(store).mount('#app')

Plugin entry file

In the entry file, export all methods directly.

// sky-vuex/index.ts
export * from './main/index'

Create a store and mount the corresponding data on the root component

The store itself is an object that contains state properties and methods such as commit and dispatch. The main functions of the store are to allow all components to get the store object to obtain the data in the state and call related methods to modify the state.

// sky-vuex/main/index.ts
import {inject, reactive, readonly} from 'vue'

const mainStoreSky = Symbol('main store key')

interface storeOptions {
  state?: any
  actions?: any
  mutations?: any
}

export const createStore = (options: storeOptions = {}) => { // Create a store object const initOptions = {
    state: {},
    actions: {},
    mutations: {},
  }

  const mergeOptions: storeOptions = Object.assign(initOptions, options)

  const state = reactive(mergeOptions.state)

  const store = {
    state: readonly(state),
    dispatch(eventName: string, ...args: any[]) {
      mergeOptions.actions[eventName](store, ...args)
    },
    commit(eventName: string, ...args: any[]) {
      ...
    },
  }

  return {
    install(app: any) {
      app.provide(mainStoreSky, store)
    },
  }
}

export const useStore = (): any => { // Other components use this method to obtain the store object return inject(mainStoreSky)
}

Implementing mapState, mapMutations, and mapActions methods

export const mapState = () => {
  const store = useStore()
  return store.state
}

export const mapActions = (eventName: string) => {
  const store = useStore()
  return (...args: any[]) => store.dispatch(eventName, ...args)
}

export const mapMutations = (eventName: string) => {
  const store = useStore()
  return (...args: any[]) => store.commit(eventName, ...args)
}

Used in components

// store/index.ts
import { createStore } from '../sky-vuex/index'

export default createStore({
  state: {
    age: 18
  },
  mutations:
    setAge(state: any, data: number) {
      state.age = data
    }
  },
})

// Home.vue
<template>
  <div class="home">
    <button @click="handleAge(23)">Modify data</button>
    <h1>{{ state.age }}</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore, mapActions, mapMutations } from '@/sky-vuex/index'

export default defineComponent({
  name: 'Home',
  setup() {
    const store = useStore()

    const handleAge = mapMutations('setAge')
    // const handleAge = mapActions('setAge')

    // const handleAge = () => {
    // store.dispatch('setAge', 5)
    // }

    return {
      state: store.state,
      handleAge,
    }
  },
})
</script>

Summarize

So far, the basic Vuex functions have been implemented. You can practice it yourself and optimize it. If you have any questions, you are welcome to ask

This is the end of this article about how to use provide in vue3 to implement state management. For more information about vue3 provide to implement state management, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Vue front-end development auxiliary function state management detailed example
  • The practical process of login status management in the vuex project
  • Quickly master how to get started with Vuex state management in Vue3.0
  • How to understand Vue's simple state management store mode
  • Application of mapState idea in vuex
  • How to use vuex in Vue project
  • Use of vuex namespace
  • Vue state management: using Pinia instead of Vuex

<<:  HTML table markup tutorial (9): cell spacing attribute CELLSPACING

>>:  Detailed explanation of the implementation process of Nginx enabling Brotli compression algorithm

Recommend

Summary of some common methods of JavaScript array

Table of contents 1. How to create an array in Ja...

Docker mounts local directories and data volume container operations

1. Docker mounts the local directory Docker can s...

jQuery implements simple pop-up window effect

This article shares the specific code of jQuery t...

Django+vue registration and login sample code

register The front-end uses axios in vue to pass ...

How to configure tomcat server for eclipse and IDEA

tomcat server configuration When everyone is lear...

MySQL-group-replication configuration steps (recommended)

MySQL-Group-Replication is a new feature develope...

How to fix the four sides of the table to scroll up, down, left and right

question: When I was doing project statistics rec...

Tomcat class loader implementation method and example code

Tomcat defines multiple ClassLoaders internally s...

MySQL 8.0.22 installation and configuration method graphic tutorial

This article records the installation and configu...

Detailed explanation of common usage of MySQL query conditions

This article uses examples to illustrate the comm...

HTML hyperlink style (four different states) setting example

Copy code The code is as follows: <style type=...

JavaScript MouseEvent Case Study

MouseEvent When the mouse performs a certain oper...

Some data processing methods that may be commonly used in JS

Table of contents DOM processing Arrays method Su...

Small problem with the spacing between label and input in Google Browser

Code first, then text Copy code The code is as fol...