Home  >  Article  >  Web Front-end  >  How to implement idle state reset in vuex

How to implement idle state reset in vuex

亚连
亚连Original
2018-06-13 17:20:451621browse

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
});

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

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

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
  }
}

Global module configuration

Define global mutation event type

// store/types.js
export const RESET_STATES = 'resetStates'

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);
    }
  },

}

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);
  }
}

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>

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:
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