You may not need to use Vuex for Vue 3

tags: java  python  vue  react  database

Vuex is a great state management library. It is simple and can be well integrated with Vue. Why would anyone leave Vuex? The reason may be that the upcoming version of Vue 3 exposes the underlying reaction system and introduces a new method of building applications. The new reaction system is very powerful and can be used for centralized state management.

Do you need to share status?

In some cases, data flow between multiple components becomes so difficult that you need centralized state management. These situations include:

Multiple components using the same data Multiple root components with data access permissions are deeply nested If none of the above is true, the answer is simple whether you need it or not. no need

But what if you have one of the following situations? The most straightforward answer is to use Vuex. This is a tried and tested solution, and it does a good job.

But what if you don’t want to add other dependencies or find that the setup is too complicated? The new Vue 3 version and Composition API can solve these problems through its built-in methods.

New solution

The shared state must meet two conditions:

Reactivity: When the state changes, the components that use them should also update Availability: The state can be accessed in any component Reactivity Vue 3 exposes its reaction system through many functions. You can use the reactive function to create reactive variables (the alternative is the ref function).

import { reactive } from 'vue';

export const state = reactive({ counter: 0 });

The Proxy object returned from the reactive function is an object whose property changes can be tracked. When used in a component template, the component will re-render itself whenever the reactive power value changes.

<template>
  <div>{{ state.counter }}</div>
  <button type="button" @click="state.counter++">Increment</button>
</template>

<script>
  import { reactive } from 'vue';

  export default {
    setup() {
      const state = reactive({ counter: 0 });
      return { state };
    }
  };
</script>

Availability

The above example is very useful for a single component, but other components cannot access the state. To overcome this problem, you can use provide and inject methods to provide any available value in the Vue 3 application.

import { reactive, provide, inject } from 'vue';

export const stateSymbol = Symbol('state');
export const createState = () => reactive({ counter: 0 });

export const useState = () => inject(stateSymbol);
export const provideState = () => provide(
  stateSymbol, 
  createState()
);

When you pass the Symbolas key and a value to the provide method, any child components in the method can use the value to inject. When Symbol provides and retrieves the value, the key uses the same name.

This way, if you provide a value on the topmost component, it will be available in all components. Alternatively, you can also call to provide the main application instance.

import { createApp, reactive } from 'vue';
import App from './App.vue';
import { stateSymbol, createState } from './store';

const app = createApp(App);
app.provide(stateSymbol, createState());
app.mount('#app');
<script>
  import { useState } from './state';

  export default {
    setup() {
      return { state: useState() };
    }
  };
</script>

Make it strong

The above solution works, but there is a disadvantage: you don't know who modified what. The status can be changed directly without restriction.

You can make it protected by wrapping the state with the readonly function. It overwrites the passed variable in the object that the Proxy prevents any modification (a warning will be issued when trying). Mutations can be handled by a separate function that can access and write storage.

import { reactive, readonly } from 'vue';

export const createStore = () => {
  const state = reactive({ counter: 0 });
  const increment = () => state.counter++;

  return { increment, state: readonly(state) };
}

The outside world will only have access to the read-only state, and only exported functions can modify the writable state.

By protecting the state from unnecessary modifications, the new solution is relatively close to Vuex.

Summary

By using Vue 3's reactive system and dependency injection mechanism, we have transformed from local state to centralized state management that can replace Vuex in smaller applications.

We have a state object that is read-only and reacts to changes in the template. The state can only be modified by specific methods such as actions/mutations in Vuex. You can use the computed function to define other getters.

Vuex has more features, such as module handling, but sometimes we don't need it.

If you want to learn about Vue 3 and try this state management method, check out my Vue 3 playground.

Intelligent Recommendation

Design a boutique in a website, you may need it-Issue 3

Public number: Mr. Kong Ming This article probably 450 words Reading needs 2 minutes Yesterday I talked about the second consecutive update, went to the appointment on time, last issuePoke thisIn this...

Teach you how to use vuex in vue-cli and an introduction to vuex

Write in front: This article is a minimalist demo of using vuex in vue-cli, with a brief introduction to vuex. Friends in need can do it for reference, like if you like, or pay attention to it, hoping...

vue Failed to resolve loader: stylus-loader You may need to install it.

  problem:   In the project operation, the problem as shown in the following figure, the fact that failed to resolve loader: Stylus-loade problem is because LANG = "stylus" is used...

vue Failed to resolve loader: sass-loader You may need to install it

Vue runs in Vue error:Failed to resolve loader: sass-loader You may need to install it. Tip is to install the SASS module. Install Node-Sass Install Sass-Loader...

(Essence updated on May 14, 2020) Vue actual combat The use of vuex and the use of vuex auxiliary functions

Basic use of vuex store.js main.js mount store.js Use in vue components Use of auxiliary functions of vuex First go to store.js main.js Use of mapstate assistance mapgetter use Use of mapmutation Use ...

More Recommendation

Oracle often uses statements that you may need to use sometimes

Written in front: The following are some of the statements that may need to be used in the work. Some of the statements that have been sorted out by various sorts are useful. If the query is incorrect...

Use Scala Map's mapValues ​​with caution, you may need transform

Before stepping on the pit of mapValues, I believe most people would think that the logic of mapValues ​​is the same as all other map methods: apply a map function to all values ​​in the Map and retur...

Points you may need to pay attention to during the use of RestTemplate

When RestTemplate sets parameters in a get request, the parameters followed by the url must not be the param value after encode, because it will encode again A URL can be encoded multiple times, each ...

You may need to use return in JS, summarize and explain! ! !

return value The Return statement terminates the function execution and returns a specified value to the caller of the function (function name + () is equal to the return value of the function) If the...

【you may need to restart the kernel to use updated packages】

@PIP Insatll command is not installed in the third party library you may need to restart the kernel to use updated packages When the PIP Install command cannot be installed in the Jupyter, the third -...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top