Table of Contents
1. Vuex
Preface
1.1. Download and configure Vuex
1.1.1. Download Vuex
1.1.2. Configure Vuex
1.2. Use of Vuex
1.2.1. state attribute
1.2.2. mutations attribute
1.2.3. getters attribute
1.3. Practical development and application
1.3.1, Vuex and LocalStorage implement dynamic maintenance of login status
一、Vuex
Foreword
Vuex is a tool for unified state management.
In the past, if you need to share data from one component to other components, you need to use props, which can only be passed in one direction. Once the status of a certain shared data is modified, other components need to be notified to update, which is very inconvenient to operate. With Vuex, it is equivalent to having a center for sharing data, and the shared data is dynamically updated.
1.1, download and configure Vuex
1.1.1, download Vuex
Enter the following command to install (suitable version for Vue2):
npm install [email protected]
1.1.2, Configure Vuex
a) Create a store folder in the src directory of the scaffolding project, create an index.js file inside to represent the entrance, and configure the following content:
import Vue from "vue"; import Vuex from "vuex" Vue.use(Vuex); //Configure vue to register vuex export default new Vuex.Store({ });
Ps; the future shared data status is configured in Vuex.Store
b) Register state management in main.js
import Vue from 'vue' import App from './App' import router from './router' //vuex import store from './store' Vue.prototype.$store = store; Vue.config.productionTip = false /* eslint-disable no-new */ newVue({ el: '#app', router, store, //Register vuex components: {App}, template: '<App/>' })
1.2, Use of Vuex
1.2.1, state attribute
state is used to define a series of shared data.
For example, there is a count data that needs to be shared among multiple components. The operation is as follows:
a) Define state in Vuex.Store
export default new Vuex.Store({ state: { //Define public data. Use shared components: this.$store.state.count count: 1 } });
b) Used in components that need to be shared
Use shared components: this.$store.state.count can also be abbreviated as $store.state.count
<h1>Manual management list --- {<!-- -->{ this.$store.state.count }}</h1>
1.2.2, mutations attribute
Mutations are used to define modification methods to shared data.
For example, add + 1 and – 1 to the shared data count.
a) Mutations defined in Vuex.Store
export default new Vuex.Store({ state: { //Define public data. Use shared components: this.$store.state.count can also be abbreviated as $store.state.count count: 1 }, mutations: { //The methods defined here have a default parameter, which is the state above. You can get the parameters inside through the state. incrCount(state) { state.count + + ; }, decrCount(state) { state.count--; } } })
b) Used in components that need to be shared
Usage: this.$store.commit(‘method name’)
<h1>Manual management list --- {<!-- -->{ this.$store.state.count }}</h1> -------------------------------------------------- ----- methods: { incr() { this.$store.commit('incrCount'); },
1.2.3, getters attribute
Getters are used to write methods for calculating shared data, which are equivalent to computed in components.
Advantages: high efficiency, only calculated once (calculation result cache).
a) Getters defined in Vuex.Store
export default new Vuex.Store({ state: { //Define public data. Use shared components: this.$store.state.count can also be abbreviated as $store.state.count count: 1 }, mutations: { //The methods defined here have a default parameter, which is the state above. You can get the parameters inside through the state. incrCount(state) { state.count + + ; }, decrCount(state) { state.count--; } }, getters: { //Used to define a series of calculation methods for shared data (the methods defined here have a default parameter, which is the state above, and the parameters inside can be obtained through the state) countSqrt(state) { return state.count * state.count; } } })
b) Used in components that need to be shared
Usage: this.$store.getters.countSqrt
<h1>Manual management list --- {<!-- -->{ this.$store.getters.countSqrt }}</h1>
1.3, actual development and application
1.3.1, Vuex and LocalStorage realize dynamic maintenance of login status
Let’s first take a look at the difference between the two:
- What vuex saves is state, which is stored in memory; localStorage is an interface provided by the browser, which allows you to save the interface and save it locally in the form of a file.
- vuex is used to transfer values between components, and localStorage is mainly used to transfer values between pages.
- When the page is refreshed, the value stored by vuex will be lost, but localStorage will not
localStorage can replace vuex, and it is indeed possible for unchanged data. However, when two components are used together as a data source, if the data source in one component changes and you want the other component to respond to the change, you must choose to use vuex at this time.
For example, dynamically maintain login status:
The store of Vuex is as follows
Vue.use(Vuex); //Configure vue to register vuex export default new Vuex.Store({ //Define global data state: { //Maintain user login status user: { id: localStorage.getItem("id"), username: localStorage.getItem("username"), isAdmin: localStorage.getItem("isAdmin"), state: localStorage.getItem("state") //0 normal (default) 1 disabled } }, mutations: { //Update login status login(state, user) { state.user.id = user.id; state.user.username = user.username; state.user.isAdmin = user.isAdmin; state.user.state = user.state; //Save to localStorage to prevent page refresh and loss of vuex data localStorage.setItem("id", user.id); localStorage.setItem("username", user.username); localStorage.setItem("isAdmin", user.isAdmin); localStorage.setItem("state", user.state); }, //Delete all login status logout(state) { state.user = {}; localStorage.clear(); } }, });
The login request is as follows:
/** * Log in */ login() { //1. Non-null verification if (this.user.username == null || this.user.username == '') { Message.warning("Username cannot be empty!"); this.$refs.username.focus();//Get focus (improve user experience) return; } if (this.user.password == null || this.user.password == '') { Message.warning("Password cannot be empty!"); this.$refs.password.focus(); return; } //2.Send request instance.post('/user/login', this.user).then(success => { if (success.data.code == 1000) { //The status code is defined here according to the backend (1000 means "operation successful") //login successful //1. Save Token to localStorage const token = success.data.data.token; localStorage.setItem("token", token); //2. Save the user login information status through vux and localStorage this.$store.commit("login", success.data.data); //3. Prompt jump Message.success("Login successful, you will be redirected to the homepage~"); this.$router.push({ name: "Index" }); } else { //Login failed console.log(success.data.msg);//Get the failure information from the backend (the frontend can see it on the console) Message.error("Account or password is wrong, please try again!"); } }).catch(error => { Message.error("Server exception, please try again later!"); console.log(error); }); }
The article has been included in the official knowledge archive Vue entry skill treeVueX status managementWhat is VueX? 39407 people are studying the system