Home Web Front-end JS Tutorial How to implement idle state reset in vuex

How to implement idle state reset in vuex

Jun 13, 2018 pm 05:20 PM
vuex reset

This article mainly introduces the vuex idle state reset solution. Now I share it with you and give it as a reference.

Preface

For large single-page applications (hereinafter referred to as spa), we often use the state manager vuex to solve state sharing and state transfer between components. question. This kind of application can range from dozens of single pages to hundreds of single pages. With the frequent switching of routes, there will be more and more states in vuex corresponding to each route. In order to achieve the ultimate optimization of the page, we need to reset those idle states to reduce the memory space occupied.

What status can be reset

vuex emphasizes the use of centralized storage to manage the status of all components of the application, but we really put all the status in the store Processing, you will find it very painful to develop. If you want to have a good control over which data needs to be put into the store for management, you must first understand what problem vuex is used to solve. The vuex official website points out that it is to solve the problem of multiple components sharing state. Then we can put the shared state of multiple components into the store for management. For single-page applications, the multi-component sharing here is often a cross-routing component. If the store only stores the state shared by multiple components, then we do not need to clean up the state in vuex, because these states will be used at any time.

As business scenarios become more and more complex, a lot of logic for interacting with the background is put into components, so the code becomes very messy and vuex is not fully utilized. At this time, we can put the logic of interaction with the backend api into the action in vuex for processing, and the status returned by the backend will naturally be put into store management. After this processing, the component is only responsible for rendering data, and the logic is very clear. At this time, there will be more and more states in the store corresponding to the component as the routing switches, and these states need to be cleaned manually.

Many solutions have trade-offs. If the data interacting with the background api is placed in the component, there is no need to clean it up, but the code logic will become more messy. In addition, the plug-in vue-devtools such as vuex will not be able to monitor the changes in each request data...

When to reset the state

The effect we want When routing is switched, the status in vuex corresponding to the previous route is reset. However, routing and vuex do not have a one-to-one correspondence. If we want to achieve this effect, then we need to maintain a routing and vuex module. Correspondence relationship, this will be very cumbersome. It is better to reset all the states in vuex when the route changes.

How to clean up the idle state in vuex

The following will be explained in combination with my github example. This example creates a single-page application. When we switch the route, we will Idle status is cleared.

Transform the module status of the component corresponding to the route

In the example, the store is split into multiple modules, and the component status corresponding to the route is placed in the corresponding module. , the state shared by multiple components is managed in the top-level store. It is roughly as follows:

// store/index.js
import page1 from "./modules/page1.js";
import page2 from "./modules/page2.js";
import page3 from "./modules/page3.js";
import page4 from "./modules/page4.js";
import page5 from "./modules/page5.js";

export default new Vuex.Store({
  state,
  getters,
  actions,
  mutations,
  modules: { // 每个路由对应的 module
    page1,
    page2,
    page3,
    page4,
    page5
  },
  plugins: __DEV__ ? [createLogger()] : [],
  strict: __DEV__ ? true : false
});
Copy after login

The state of the module corresponding to route page1 is in the form:

// store/modules/page1.js
const state = {
   // 列表数据
   page1Data: [],
   // 标题数据
   page1Title: ''
}
Copy after login

These data are returned and copied by calling the backend api. If we reset it when the route changes For this data, you need to extract the initialization data and expose an identification method initState() that needs to be reset, which means that it needs to be reset when the route changes. Of course, this method name is a convention, and you can also define it as another name. After transformation:

// store/modules/page1.js
// 放置你要重置的数据
const initState = {
  page1Data: [],
}

// state
const state = {
  // 参数解构
  ...initState,

  // 路由改变不想重置的数据
  page1Title: '',
  initState(){
    return initState
  }
}
Copy after login

Global module configuration

Define global mutation event type

// store/types.js
export const RESET_STATES = 'resetStates'
Copy after login

Define global mutation

// store/mutation.js

import * as types from './types'

// 检测所有的 state 并把 `initState()` 中的属性重置
function resetState(state, moduleState) {

  const mState = state[moduleState];

  if (mState.initState && typeof mState.initState === 'function') {

    const initState = mState.initState();

    for (const key in initState) {

      mState[key] = initState[key];
    }
  }

}

export default {

  [types.RESET_STATES](state, payload) {

    for (const moduleState in state) {

      resetState(state, moduleState);
    }
  },

}
Copy after login

Define global action

// store/action.js
import * as types from './types'

export default {
  // rest state action
  resetStates:function (context, payLoad) {

    context.commit(types.RESET_STATES, payLoad);
  }
}
Copy after login

Route switching trigger reset method

Now everything is ready, you only need to trigger the reset method when the route changes, in the entry vue file Processing

// components/app.vue
<script>
  import {mapState, mapActions} from "vuex"
  export default{

    methods: {

      ...mapActions({
        resetStates: "resetStates"
      })
    },

    watch: {

      $route(to, from) {
        // 路由改变发起重置
        this.resetStates();
      }
    }
  }
</script>
Copy after login

If your chrome browser has vuejs-devtools installed, you can clearly see the reset process of the previous routing data when switching routes.

Summary

Click here for examples. Our vuex state reset here is to traverse the states in all stores every time the route is switched, and reset the properties in initState(). It would be better if we could reset the state corresponding to the current route. But there is no relationship between routing and modules in the store. Here is just a solution to reset the vuex state. If you have a better solution, please leave a message. If there is anything inappropriate, please feel free to leave a comment.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to reference Ali font icons in vue

About the actual usage of log4js in Express

How to implement WebSocket function using NodeJS

The above is the detailed content of How to implement idle state reset in vuex. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP form processing: form reset and data clearing PHP form processing: form reset and data clearing Aug 07, 2023 pm 03:05 PM

PHP form processing: form reset and data clearing In web development, forms are a very important part and are used to collect data entered by users. After the user submits the form, we usually process the form data and perform some necessary operations. However, in actual development, we often encounter situations where we need to reset the form or clear the form data. This article will introduce how to use PHP to implement form reset and data clearing functions, and provide corresponding code examples. Form reset First, we need to understand the concept of form reset. when user

WiFi calling not working on iPhone: Fix WiFi calling not working on iPhone: Fix Jun 03, 2024 am 11:16 AM

Can't enable Wi-Fi calling on iPhone? Call quality is improved and you can communicate even from remote locations where cellular networks are not as strong. Wi-Fi Calling also improves standard call and video call quality. So, if you can't use Wi-Fi calling on your phone, these solutions might help you fix the problem. Fix 1 – Enable Wi-Fi Calling Manually You must enable the Wi-Fi Calling feature in your iPhone settings. Step 1 – For this, you have to open Settings. Step 2 – Next, just scroll down to find and open the “Phone” settings Step 3 – In the phone settings, scroll down and open the “Wi-Fi Calling” setting. Step 4 – In the Wi-Fi Calling page, change “This iPhone

How to solve win11 reset problem How to solve win11 reset problem Jan 05, 2024 am 09:24 AM

After the launch of win11, many users directly updated it. However, after the update, many users experienced reset failure and did not know how to solve it. So today we bring you the solution to win11 reset failure. Come and see how it works. How to solve win11 reset failure 1. First, click Start in the lower left corner, click Settings, and then select Update and Security. 2. Click the Recovery button on the left and click Start under the Reset this PC option. 3. You can then select an option. 4. Finally, wait for the installation of win11 system to solve the problem. 5. Users can also directly download the win11 system from this site to solve the problem.

How to reset recommended content on TikTok? How to set up its recommended content? How to reset recommended content on TikTok? How to set up its recommended content? Mar 27, 2024 pm 07:30 PM

Douyin, the world's most popular short video platform, allows everyone to become a creator and share every moment of life. Sometimes we may get tired of the content recommended by Douyin and hope to reset the recommended content so that the platform can re-evaluate and push content more suitable for us. So, how does Douyin reset recommended content? This article will answer this question in detail. 1. How to reset recommended content on Douyin? Douyin makes personalized recommendations based on users’ viewing history, interactive behavior, interests and preferences and other data. Currently, the Douyin platform does not directly provide the option to reset recommended content. However, there are a few things users can do to try to reset recommended content, such as clearing their viewing history, unfollowing content creators they are not interested in, and diversifying their viewing content to change their recommendations.

Is your iPhone charging less than 80%? How to fix Is your iPhone charging less than 80%? How to fix Oct 20, 2023 am 11:33 AM

You may have noticed that sometimes, no matter how long you leave it plugged in, your iPhone never reaches more than 80% charge. The obvious conclusion might be a software or battery failure. But in fact, this could also be due to features in iOS. Unlike other parts of your iPhone, the battery can lose capacity over time. Therefore, these features are implemented as a precautionary measure to avoid rapid deterioration of the power supply. But what if you disabled this feature and your iPhone still doesn't have more than 80% battery? In this case, you can try the fixes we have listed below to help you resolve this issue on your iPhone. Is your iPhone charging less than 80%? Here's how you can fix it

What should I do if the win10 reset is stuck at 100% and unresponsive? What should I do if the win10 reset is stuck at 100% and unresponsive? Jan 07, 2024 pm 04:13 PM

If we want to reset our win10 system to solve some problems and faults, many friends do not know how to solve the problem of being stuck at 100% and unresponsive during the reset process. Then the editor thinks it may be because there are still some files that need to be compiled after the reset of our computer. Generally, it takes 3-4 hours to reset the system, so just wait patiently. Let’s take a look at what the editor said for the detailed steps~ What to do if win10 reset is stuck at 100% and unresponsive. Method 1: 1. Press the power button directly on the Hello interface that has been stuck to shut down 2. Or press Press the restart button to restart, and press ctrl+shift+f33 when Iogo appears on startup. You can enter after skipping the installation settings. There is a high probability that you can enter, but

Teach you how to diagnose common iPhone problems Teach you how to diagnose common iPhone problems Dec 03, 2023 am 08:15 AM

Known for its powerful performance and versatile features, the iPhone is not immune to the occasional hiccup or technical difficulty, a common trait among complex electronic devices. Experiencing iPhone problems can be frustrating, but usually no alarm is needed. In this comprehensive guide, we aim to demystify some of the most commonly encountered challenges associated with iPhone usage. Our step-by-step approach is designed to help you resolve these common issues, providing practical solutions and troubleshooting tips to get your equipment back in peak working order. Whether you're facing a glitch or a more complex problem, this article can help you resolve them effectively. General Troubleshooting Tips Before delving into specific troubleshooting steps, here are some helpful

How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application? How to solve the problem 'Error: [vuex] unknown action type: xxx' when using vuex in a Vue application? Jun 25, 2023 pm 12:09 PM

In Vue.js projects, vuex is a very useful state management tool. It helps us share state among multiple components and provides a reliable way to manage state changes. But when using vuex, sometimes you will encounter the error "Error:[vuex]unknownactiontype:xxx". This article will explain the cause and solution of this error. 1. Cause of the error When using vuex, we need to define some actions and mu

See all articles