vuex
Vuex is a state management mode + library developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.
What is “state management mode”?
- State, the data source that drives the application;
- Views, which declaratively map state to views;
- Action in response to changes in state caused by user input on the view.
Here is a simple illustration of the idea of “one-way data flow” :
Multiple components share state
- Multiple views depend on the same state.
- Actions from different views need to change the same state.
When should I use Vuex?
Vuex helps us manage shared state and comes with more concepts and frameworks. This requires a trade-off between short-term and long-term benefits.
Using Vuex can be tedious and redundant if you don’t plan to develop large, single-page applications. That’s true — if your application is simple, you’d better not use Vuex. A simple Store pattern is all you need. However, if you need to build a medium to large single-page application, and you’re probably thinking about how to better manage state outside of components, Vuex would be a natural choice. To quote Redux author Dan Abramov:
Page logic is complex and there are many pages
The installation
yarn add vuex@next --save
Copy the code
Initialize the store
import { createStore } from 'vuex'
const store = createStore({})
export default store
Copy the code
The introduction of the store
import { createApp } from 'vue'
import App from './App.vue'
import Antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.css';
import router from './router';
import store from './store';
// console.log(import.meta.env['VITE_APP_BASE_API'])
createApp(App).use(router).use(store).use(Antd).mount('#app')
Copy the code