Dive into Vuex: A comprehensive guide to the official Vue.js state management library

foreword

insert image description here
"Author's Homepage" : Sprite Youbai Bubbles
"Personal Website" : Sprite's personal website
"Recommendation Column" :

Java one-stop service
Front-end cool code sharing
uniapp-from construction to promotion
From 0 to hero, Vue's road to god
Solving algorithm, one column is enough
Let's talk about architecture from 0
The subtle way of data circulation

Please add a picture description

insert image description here

State Management: Understanding Vuex

What is state management

  • The concept of state management

    State management refers to a pattern for efficiently managing and sharing data within an application. It enables easy access and modification of shared data between different components by centrally storing and managing the state of the application. State management usually uses a single source of truth to store the state of the application and provides a set of standardized methods to update and retrieve the state.

  • Why state management is needed

    In large and complex applications, passing and sharing data between components can become very difficult. When multiple components need to access and modify the same data, if there is no unified way to manage these data, it will lead to code redundancy, data inconsistency and difficult maintenance problems. State management solves these problems by introducing a central data repository, making the management and sharing of data simpler and more reliable.

Here is an example code snippet demonstrating how to use Vuex for state management:

// 引入Vue和Vuex
import Vue from 'vue';
import Vuex from 'vuex';

// 使用Vuex插件
Vue.use(Vuex);

// 创建一个新的Vuex存储实例
 store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0 // 初始状态
  },
  mutations: {
    
    
    increment(state) {
    
    
      state.count++; // 修改状态的方法
    }
  },
  actions: {
    
    
    incrementAsync({
    
     commit }) {
    
    
      setTimeout(() => {
    
    
        commit('increment'); // 异步操作,调用mutation来修改状态
      }, 1000);
    }
  },
  getters: {
    
    
    doubleCount(state) {
    
    
      return state.count * 2; // 计算属性,根据状态计算派生出新的值
    }
  }
});

// 在Vue应用程序中使用Vuex存储
new Vue({
    
    
  store,
  computed: {
    
    
    count() {
    
    
      return this.$store.state.count; // 获取状态的方法
       doubleCount() {
    
    
      return this.$store.getters.doubleCount; // 获取计算属性的方法
    }
  },
  methods: {
    
    
    increment() {
    
    
      this.$store.commit('increment'); // 调用mutation来修改状态
    },
    incrementAsync() {
    
    
      this.$store.dispatch('incrementAsync'); // 调用action来进行异步操作
    }
  }
}).$mount('#app');

In the above code, we first introduced Vue and Vuex, and Vue.use(Vuex)installed the Vuex plugin into Vue. We then create a new Vuex store instance, which defines the initial state of the application, methods to modify the state (mutations), methods to perform asynchronous operations (actions), and computed properties (getters). Finally, we use objects in our Vue applications storeto get and modify state.

By using Vuex for state management, we can easily share and update data in different components. For example, in the above example, we can this.$.state.countget the state value with and this.$store.commit('increment')call the mutation method with to modify the state. At the same time, we can also use computed properties doubleCountto derive new values ​​based on state calculations.

To sum up, state management is an effective data management pattern, which simplifies the communication between components by centrally storing and managing the state of the application.

Introducing Vuex

Vuex is a state management pattern developed specifically for Vue.js applications. It centrally manages the state of all components of an application and provides a predictable way to track state changes. By using Vuex, developers can more easily manage and share the state of the application, which simplifies the state management of complex applications.

The role and advantages of Vuex

  1. Centralized storage : Vuex stores the state of the application in a single place, called the "store". This can be accessed by all components, making the management of state centralized and unified. In this way, different components can share state, avoiding the trouble of passing data between components.

  2. State predictability : Vuex uses a strict state change method, that is, the state can only be modified by submitting mutations. The advantage of this is that we can clearly track state changes, because each state change has a corresponding mutation, and all mutations are synchronized. This predictability makes debugging and testing easier.

  3. Convenient state management : Vuex provides some auxiliary functions and tools to make state management more convenient. For example, we can use helper functions like mapState, mapGetters, mapMutations, and mapActions to simplify access to state, getters, mutations, and actions.

  4. Plug-in extensibility : Vuex provides a plug-in mechanism that allows developers to inject custom logic into the store. This allows us to extend the functionality of Vuex according to specific needs, such as adding logging, persistent storage, etc.

The core concept of Vuex

  1. State (state) : that is, the state data of the application, which is stored in the store of Vuex. It can be accessed through this.$store.state.
// 在Vue组件中访问state
computed: {
    
    
  count() {
    
    
    return this.$store.state.count;
  }
}
``2. **Getter(获取器)**:用于从store中获取状态数据,并进行一些计算或转换后返回。可以通过this.$store.getters来访问。

```javascript
// 在Vue组件中访问getter
computed: {
    
    
  doubleCount() {
    
    
    return this.$store.getters.doubleCount;
  }
},
// 在Vuex的store中定义getter
getters: {
    
    
  doubleCount: state => {
    
    
    return state.count * 2;
  }
}
  1. Mutation : The only way to modify state data. Each mutation has an event type of string type and a callback function that triggers a state change by submitting the mutation.
// 在Vue组件中提交mutation
methods: {
    
    
  increment() {
    
    
    this.$store.commit('increment');
  }
},
// 在Vuex的store中定义mutation
mutations: {
    
    
  increment: state => {
    
    
    state.count++;
  }
}
  1. Action (action) : used to handle asynchronous operations or batch mutations. Actions can be triggered by this.$store.dispatch.
// 在Vue组件中触发action
methods: {
    
    
  fetchData() {
    
    
   .$store.dispatch('fetchData');
  }
},
// 在Vuex的store中定义action
actions: {
    
    
  fetchData:({
    
     commit }) => {
    
    
    // 异步操作
    // 调用mutation来修改状态
    commit('setData', data);
  }
}
  1. Module (module) : used to divide the store into multiple modules, each module has its own state, getters, mutations and actions. This allows for better organization and management of the state of large applications.
// 在Vuex的store中定义模块
modules: {
    
    
  moduleA: {
    
    
    state: {
    
     ... },
    getters: {
    
     ... },
    mutations: {
    
     ... },
    actions: {
    
     ... }
  },
  moduleB: {
    
    
    state: {
    
     ... },
    getters: {
    
     ... },
    mutations: {
    
     ... },
    actions: {
    
     ... }
  }
}

Steps to use Vuex

  1. Install Vuex: Install the Vuex library via npm or yarn.

  2. Create a store: Create a store instance in the entry file of the Vue application, and configure state, getters, mutations, actions, etc.

  3. Use Vuex in Vue components: access state data in the store through this.$store, and use helper functions to simplify access to state, getters, mutations, and actions.

  4. Submit a mutation or trigger an action: Submit a mutation through the commit method to modify the state, or trigger an action through the dispatch method to handle asynchronous operations.

In short, Vuex is a powerful state management library that can help us better manage the state of Vue.js applications. It provides a centralized storage method that makes state management simple and predictable. By using Vuex, we can better organize and share the state of the application, improving development efficiency and code quality.

Vuex is a state management pattern developed specifically for Vue.js applications. It can help us centrally manage and share state in the application, making state changes more traceable and maintainable. The basic usage of Vuex will be introduced below.

Install and configure Vuex

First, we need to install Vuex. You can use npm or yarn to install:

npm install vuex

After the installation is complete, import and configure Vuex in the entry file (usually main.js) of the Vue application:

import Vue from 'vue';
import Vuex 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
    
    
  // 在这里定义你的状态、getters、mutations和actions
});

new Vue({
    
    
  store,
  // ...
}).$mount('#app');
``### 定义和使用状态
在Vuex中,我们可以通过定义state来存储应用程序的状态数据。state是响应式的,当状态发生变化时,相关的组件会自动更新。

```javascript
const store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  }
});

To use state in components, it can be this.$store.stateaccessed using:

// 在组件中获取状态
computed: {
    
    
  count() {
    
    
    return.$store.state.count;
  }
}

Get state using Getters

Sometimes we need to perform some calculations or filters on the state, then we can use getters. Getters can be seen as computed properties of the store, which will be cached according to the state of the dependency, and will only be recalculated when the dependency changes.

const store = new Vuex.Store({
    
    
  state: {
    
    
    todos: [
      {
    
     id: 1,: 'Todo 1', done: true },
      {
    
     id: 2, text: 'Todo 2', done: false },
      // ...
    ]
  },
  getters: {
    
    
    doneTodos: state => {
    
    
      return state.todos.filter(todo => todo.done);
    }
  }
});

Use getters in components:

// 在组件中获取计算后的状态
computed: {
    
    
  doneTodos() {
    
    
    return this.$store.getters.doneTodos;
  }
}

Modify state using Mutations

To modify state, we need to use mutations. mutations is an object containing various methods for modifying state. Each method receives the state as the first parameter, and can receive additional parameters to modify the state.

const store = new.Store({
    
    
  state: {
    
    
    count: 0
   mutations: {
    
    
    increment(state) {
    
    
      state.count++;
       incrementBy(state, amount) {
    
    
      state.count += amount;
    }
  }
});

Submit the mutation in the component:

// 在组件中提交mutation
methods: {
    
    
  increment() {
    
    
   .$store.commit('increment');
   incrementBy(amount) {
    
    
   .$store.commit('incrementBy', amount);
  }
}

Use Actions to handle asynchronous operations

Sometimes we need to perform asynchronous operations in mutation, then we can use actions. Actions are similar to mutations, but can contain asynchronous operations.

 store = new Vuex.Store({
    
    
  state: {
    
    
    count: 0
  },
  mutations: {
    
    
    increment(state) {
    
    
      state.count++;
    }
  },
  actions: {
    
    
    incrementAsync(context) {
    
    
 setTimeout(() => {
    
    
        context.commit('increment');
      }, 1000);
    }
  }
});

Distribute actions in components:

// 在组件中分发action
methods: {
    
    
  incrementAsync() {
    
    
    this.$store.dispatch('incrementAsync');
  }
}

Advanced usage of Vuex

Vuex is a state management library for Vue.js applications. It provides a way to centrally store and manage the state of all components in an application. In addition to the basic state management functions, Vuex also provides some advanced usage, which can help us better organize and extend the state of the application.

Modular Organizational State

In large applications, state can become very complex. In order to better organize and manage the state, Vuex allows us to split the state into modules. Each module has its own state, actions, getters and mutations. This makes the code more maintainable and extensible.

Here is an example showing how to organize state using modularity:

// store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const moduleA = {
    
    
  state: {
    
     ... },
  mutations: {
    
     ... },
  actions: {
    
     ... },
  getters: {
    
     ... }
};

const moduleB = {
    
    
  state: {
    
     ... },
  mutations: {
    
     ... },
  actions: {
    
     ... },
  getters: {
    
     ... }
};

const store = new Vuex.Store({
    
    
  modules: {
    
    
    moduleA,
    moduleB
  }
});

export default store;

In the example above, we defined two modules moduleAand moduleB, and added them to modulesthe options. Each module has its own state, mutations, actions and getters.

Extend Vuex functionality with plugins

In addition to basic state management functions, Vuex also allows us to use plugins to extend its functionality. Plugins can be used to add global logic, middleware, and other additional functionality.

Here is an example showing how to extend Vuex functionality using plugins:

// logger.js

const logger = store => {
    
    
  store.subscribe((mutation, state) => {
    
    
    console.log('mutation type:', mutation.type);
    console.log('mutation payload:', mutation.payload);
  });
};

export default logger;
// main.js

import Vue from 'vue';
import Vuex from 'vuex';
import logger from './logger';
import store from './';

Vue.use(Vuex);

const myPlugin = store => {
    
    
  // 在这里添加你的插件逻辑
};

store.plugin(logger);
.plugin(myPlugin);

new Vue({
    
    
  store,
  // ...
});

In the above example, we defined a loggerplugin called and store.plugin()added it to the Vuex store via method. The plugin will be called every time a mutation is submitted, and we can perform some custom logic in the plugin, such as recording the type and payload of the mutation.

Debugging with strict mode

Vuex provides a strict mode to help us debug state changes in our application. In strict mode, all modifications to the state must be made through mutation functions, otherwise an error will be thrown.

Here is an example showing how to enable strict mode:

// store.js

 store = new Vuex.Store({
    
    
  // ...
  strict: true
});

In the example above, we strictset the option to true, to enable strict mode. Once strict mode is enabled, Vuex will throw an error if we modify the state directly without using a mutation function. This helps us catch inappropriate use of state changes and helps us debug and maintain the application.

Guess you like

Origin blog.csdn.net/Why_does_it_work/article/details/131790443