What is Vuex
🤔 website explains: The core of each Vuex is store. Store is basically a container that contains most of the states in the application. Vuex is a state management mode specially developed for vue.js applications. This state self-management application consists of three parts: ①State drives the application data source; ② View maps state to view declaratively; ③ Actions respond to state changes caused by user actions on view
What scenarios require Vuex
- User login status, name, profile picture, and location
- Items in the shopping cart and items in your collection
To sum up… Vuex can be used for a range of scenarios that may involve multiple views depending on a state, or where the behavior from different views needs to change the same state!
Differences between Vuex and global variables
🤯 Global variables: The data on Vue. Propertype is static and can only be manually modified. Components that use this data will not be re-rendered. 😇 Vuex: The data in VUEX is responsive. As long as the data in store is updated, the components of store will be rendered immediately. If you want to modify the data in store, the action/mutation layer will be used, which is clearly divided and easy to manage. And the data is responsive
🤪 enough for a brief introduction to Vuex!
How do I install Vuex
Enter the project open command line, type NPM install vuex –save press Enter to install.
Then configure vuex to work by creating a store/index.js file in the SRC path:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); Const store = new vuex. store ({state: {// define string name for global use name: 'zhang SAN'},}); export default store;Copy the code
Modify the main. Js:
import Vue from 'vue'; import App from './App'; import router from './router'; import store from './store'; New Vue({el: '#app', router, store, // Add store object to Vue instance components: {app}, template: '< app />'});Copy the code
Last modify app.vue:
<template> <div></div> </template> <script> export default {mounted() {// Use this.$store.state console.log(this.$store.state.name); } } </script>Copy the code
🤩 Type NPM run dev on the command line to start the project. You great guy, got a VuEX project up and running in less than a cup of tea! Go to the console and look at the value of name we defined in store.
🤩 guys, we’re going to start learning a little more advanced usage!