1. What is Vuex
Vuex is a state management model specially developed for Vue.js applications . It uses centralized storage to manage the state of all components of the application and solve multi-component data communication.
Main points:
- Vue official collocation, exclusive use (similar to: vue-router), with special debugging tools
- Centralized management data status scheme (more concise operation)
data() { return { 数据, 状态 }}
- Data changes are predictable ( responsive )
2. Vuex-Use Vuex in Vue project
- Case 1: Used in old projects. First install the vuex package additionally, and then configure it.
- Case 2: Used in a new project. When configuring vue-cli to create a project, you can directly select the vuex item, so you don't need to do any configuration (scaffolding will automatically complete it for us). The details are as follows:
1.2 Installation
Since it is done after VueX
learning , please refer to the built directory for the directory of the project that appears below.VueCli
VueCli 2.x
The premise of the following steps is that you have completed the construction of the Vue project and have moved to the file directory of the project.
-
Npm install Vuex
-
Only the first case is described here. Using vuex in the old project
assumes that there is already a vue project before, and vuex is not used in it, let's use it now.
Note that the process of creating a project with vue scaffolding is omitted here.
Overall steps:
1 installation. It is a separate package and needs to be installed first.
2 Configure
a to create a Vuex.store instance
b to inject the store into the Vue instance
3 to use. Use the store installation package in the component
: enter the project directory, install the package
npm install [email protected]
development dependencies: npm i xxxx --save-dev ; npm i xxxx -D ;
production dependencies: npm i xxxx --save ; npm i xxxx -S; npm i xxxx
1.3.1 The instantiated store
is the same as the router. After we use vuex in the project, in order to facilitate code maintenance, we generally need to make special directory adjustments. The agreed structure is as follows:
Place the specific code in store/index.js, as follows:
1.3.2 Inject store into Vue instance
In src/main.js:
- import store
- and inject the Vue instance
Use the store in the component
In any component, pass this.$store.state
to get public data.
1.3.3 Using Vuex in components
For example, in App.vue, we want to display the name defined in the state in the h1 tag
<template>
<div id='app'>
name:
<h1>{
{ $store.state.name }}</h1>
</div>
</template>
or to use in component method
...,
methods:{
add(){
console.log(this.$store.state.name)
}
},
...
Note, please do not change state
the value of the state in here.
1.4 Install the Vue development tool VueDevtools
In Vue project development, it is necessary to monitor various values in the project. In order to improve efficiency, Vue provides a browser extension - VueDevtools.