The way data is shared between components

  • The parent passes values to the child using the property bind v-bind

  • The child passes the value V-on to the parent using the event binding

  • Sharing data between sibling components: EventBus

    • $on The component that receives the data

    • Which component $emit sends data to

What is Vuex

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the status of all components of applications, which makes it more convenient to realize data sharing among components.

Advantages of using Vuex to manage data

  • Centralized management of shared data in Vue facilitates development and maintenance
  • It can realize data sharing among components and improve development efficiency
  • The data stored in Vuex is responsive, and whenever the data is changed, the data in the page is updated synchronously.

Scenarios using Vuex

  • In general, only data that is shared between arrays is necessarily stored in Vuex
  • A component’s private data is stored in its own component’s data

Basic use of Vuex

  • Installation Scheme 1
  1. NPM installs Vuex dependency packages

    npm install vauex --save 
    Copy the code
  2. Import Vuex package

    Import Vuex from "Vuex" vue. use(Vuex) // Mount to VueCopy the code
  3. Creating a Store object

    const store=new Vuex.Store({
      //state stores globally shared dataState: {count:0}})Copy the code

    4. Mount the Store object to the Vue instance

  • new Vue({
     el:"#app".render:h= >(app),
     router,
     // All components can get global data directly from store
     store
    })
    Copy the code
  • Installation Scheme 2

  1. Open the terminal and enter the command vue UI

  2. Create the project and set the project name and package manager

  3. Set the manual configuration item

  4. Setting function Items

  5. Standard configuration, create projects.

Core features in Vuex

State (data)

  • Component to access data in StateMethods a

State provides the only common data source where all shared data is stored

// Create a store data source that provides unique public data
const store= newVuex. Store ({state: {count:0}})Copy the code
// The first way to access data in State in an interpolation expression in a component
this$store.state. Global data nameCopy the code
  • Component to access data in StateWay 2
// Import mapState functions from vuEX as needed
import {mapState} from 'vuex'

Copy the code
// Map global data needed by the current component to computed properties of the current component using the mapState function you just imported
  computed: {... mapState(['count']) // Use the extension operator... MapState can be mapped to computed properties of the current component
  }
Copy the code

Mutation (method)

Mutation cannot execute asynchronous tasks. Asynchronous tasks need Action

  • Mutation is used to change data in the Store(the way a)
    • Store data can only be changed by Mutation, but data in Store cannot be manipulated directly
    • This is a slightly more cumbersome way to operate, but you can monitor all data changes centrally
    • Use this. Codestore.mit in the component’s methods to get the mutation methods
    • Parameters can be passed when mutation is triggered
    <script>
       // Mutation is defined in the store. vue file
     const store=new Vuex.Store({
       state: {count:0
       },
       mutations: {// Change data only, no parameter is passed
         add(state){
          // Change the stateThe state count++},// The step parameter is passed when mutation is triggered
         addN(state,step){
          // Change the data
          state.count+=step
        } 
       }
     })
     <script>
    
    Copy the code
     <script>
    // Use trigger Mutation in the component
      methods:{
        handle1(){
       //commit is used to trigger a function of mutation
        this.$store.commit("add")}handle2(){
         //commit is used to trigger the mutation function and carry parameters
         this.$store.commit("addN".3)
        }
      }
    <script>
    Copy the code
  • Trigger mutationWay 2
    • Import the mapMutations function from Vuex on demand

      // Import the mapMutations function from VUEX on demand
       import {mapMutations} from "vuex"
      Copy the code
    • Through the newly imported mapMutations function, the required mutations function is mapped to the methods of the current component

      The use of… Extension operators can also pass arguments

      <script>
      // Map the mutations function to the methods function of the current componentMethods: {... mapMutations(["add"."addN"])  //add, and addN is the mutation method
         handle1(){
           this.add() // Use the add method of mutation},handle2(){
          this.addN(3) // use the addN method of mutation and pass parameter 3
         }
      }
      <script>
      Copy the code

Action (Performing asynchronous tasks)

Action is used to process asynchronous tasks

  • Trigger the Action asynchronous taskMethods a
    • To manipulate asynchronously changed data, you must use the Action, not Mutation, but must do so in the ActionChange data indirectly by triggering Mutation
    • Used in componentsThis.$store.dispatch(" method name ")Trigger Action
<script>
// In the store.vue file
const store=new Vuex.store({
   state: {count:0
   },
  mutations: {add(state){
      state.count++
    },
    addN(state){
      state.count++
    }
  },
  actions: {// Actions handles asynchronous operations
    addAsync(context){
     setTimeout(() = >{
       context.commit("add") //commit triggers the add method of mutation
      },1000)},addNAsync(context,step){
      setTimeout(() = >{
        context.commit("addN",step)//commit triggers the mutation addN and carries the step parameter
      },1000)
    }
  }
})
<script>
Copy the code
<script>
// Use trigger actions in the component
methods:{
  handle1(){
    // The first way to trigger actions
     this.$store.dispatch("addAsync")},handle2(){
     // Dispatch triggers asynchrony of actions and carries parameters
      this.$store.dispatch("addNAsync".5)
   }
 }
<script>
Copy the code
  • Trigger Action Asynchronous task mode 2

    • . MapActions (” method name “) is the second way to trigger actions

      // Import mapActions functions from vuex as needed
       import mapActions from "vuex"
      Copy the code
    • Map the required Actions functions to the current component’s methods using the newly imported mapActions function

      <script>
      // Map the actions function to the methodes function of the current componentmethods{ ... mapActions(["add"."addN"])
         handle1(){
           this.add() // Use the add method of mutation},handle2(){
          this.addN(3) // use the addN method of mutation and pass parameter 3
         }
      }
      <script>
      Copy the code

Getter (process forming new data)

  • Getters are used to process the data in the Store to form new data, similar to the calculation properties of Vue

  • The data in the Store changes, the data in the Getter changes

    <script>
    // Define the Getter in the store file
     const store= newVuex. Store ({state: {count:0
        },
        getters: {// Defines the showNum function
         showNum:state= >{
            return:"The current latest data is' +state.count+ '"
          } 
        }
     })
    <script> 
    Copy the code
  • The first way to use getters in a component is:

    this.$store.getters. Function nameCopy the code
  • The second way to use getters. Map…

  • Note that it needs to be used in computed properties

    import {mapGetters} from "Vuex"
    computed: {... mapGetters({"showNum"})}Copy the code

Module (split into modules)

Application scenario: Store,mutation, Action,getter when the project becomes very complex. You can get quite bloated. Modules are split into modules for easy management

  • Global definitions

    ModuleA and moduleB modules are globally defined and finally registered in modules
    const moduleA = {
      state: () = >({... }),mutations: {... },actions: {... },getters: {... }}const moduleB = {
      state: () = >({... }),mutations: {... },actions: {... }}const store = createStore({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    ​
    store.state.a // -> moduleA status
    store.state.b // -> moduleB status
    Copy the code
  • The module name

    Be careful not to conflict by defining two identical getters in different, namespaceless modules

    • Adding namespaced: True makes it a named module, which makes it more reusable and encapsulation

    • When a module is registered, all its getters, actions, and mutations are automatically named according to the path the module was registered with. For example: the commit (‘ account/login)

      const store = createStore({
        modules: {
      / / parent module
          account: {
            namespaced: true.// Module assets
            state: () = >({... }),// Module states are already nested, and using the 'namespaced' attribute doesn't affect them
            getters: {
              isAdmin () { ... } // -> getters['account/isAdmin']
            },
            actions: {
              login () { ... } // -> dispatch('account/login')
            },
            mutations: {
              login () { ... } // -> commit('account/login')
            },
      ​
            // Nested modules
            modules: {
              // Inherits the parent module's namespace
              myPage: {
                state: () = >({... }),getters: {
                  profile () { ... } // -> getters['account/profile']}},// Further nested namespaces
              posts: {
                namespaced: true.state: () = >({... }),getters: {
                  popular () { ... } // -> getters['account/posts/popular']}}}}}})Copy the code

Adjustments to access data and modify data

  • To access data in a module, add the module name

    Get the data item: {{$store.state. Module name. Getters: {{$store. Getters [$store.'Module name /getters name']}}
    Copy the code
  • Access mutations/ Actions in the module:

    • If namespaced is true, you need to add an additional module name
    • If namespaced is false, no additional module name is required
    $store.commit('mutations name')        / / namespaced to false
    $store.commit('Module name /mutations name')  / / namespaced to true
    Copy the code

“Likes, favorites and comments”

❤️ follow + like + favorites + comments + forward ❤️, encourage the author to create a better article, thank 🙏 everyone.