How to use vuex and how to perform route guarding

2.1. What is vuex?

Vuex is a state management pattern developed specifically for Vue.js applications. It uses centralized storage to manage the status of all components in the application, and uses corresponding rules to ensure that the status changes in a predictable way.

2.2. Why use vuex?

  • Carry out unified status management and solve the problem of different components sharing data.

  • The problem of different views needing to change the same state.

  • After using vuex, status changes are clearer.

  • 2.3. How to use vuex?

  • Installation introduction npm install vuex --save

  • Register into vue

  • import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)

  • Instantiate the vuex store

  • const store = new Vuex.Store({
        state: {
            count: 0,
            title:'vuex中的title'
        },
        mutations: {
            increment(state,count) {
                state.count=count
            }
        }
    })

  • Mounted on vue instance

  • new Vue({
        store
    })

  • In the component, you can operate vuex through this.$store.

  • 2.4. Core concepts

    2.4.1、state

  • What is state? It is a single state tree, which is the only data source in vuex. Our data is placed in state.

  • To get the value of state in the component, pass this.$store.state.

  • Or it can be obtained through calculated properties, mapState auxiliary function, which can simplify the operation

  •  import {mapState} from "vuex";
    computed: {
        // 可以写一些其他的计算属性
        ...mapState({
          // title: state => state.title
          // title: "title"
          title: state => {
            return state.title;
          }
        })
      }

    2.4.2、getters

  • Process (derive) the data in state

  • Get the value in getters through this.$store.getters,

  • Or get it through calculated attributes. Getters also have auxiliary functions mapGetters. The usage is the same as mapState.

  •   import { mapGetters} from "vuex";

  • computed: {

  •     // You can write some other calculated properties

  •     ... mapGetters ({

  •       title: "title"

  •     })

  •   }

  • 2.4.3、mutation

  • Modify the value in state. Every time our state changes, it should be modified by mutation to facilitate tracking the flow of data.

  • Define mutation

  • const store = new Vuex.Store({
            // ....
        mutations: {
            increment(state, count) {
                state.count = count
            },
            [CHANGE_TITLE](state, payload) {
                state.title = payload.title;
                // 不能这么写的
                state.obj = {
                    ...state.obj,
                    title:payload.title
                }
            }
        }
    })

  • Call mutation

  • this.$store.commit('mutation type (function name)', "Parameters, parameters are generally in object form")

  • this.$store.commit({type:'mutation type (function name)'},...other parameters)

  • Precautions

  • We must follow the rules of Vue's corresponding changes, which simply means that when assigning objects, we must replace old objects with new objects.

  • The mutation type or function name can be maintained with constants.

  • Mutation functions must be synchronous.

  • 2.4.4、action

  • Action is similar to mutation, except that

  • Action can contain asynchronous operations

  • Action cannot directly modify state. If you want to modify state, you need to trigger mutation.

  • 2. How to define?

  •  actions: {
        // 通过context(上下文环境)可以触发mutation,触发action,获取state、getter等操作
            // 第二个参数就是我们传递过来的参数
            changeTitle(context,payload) {
                setTimeout(() => {
                    context.commit(CHANGE_TITLE, payload)
                }, 1000);
            }
        }

  • How to trigger action

  • this.$store.dispatch('action name','parameters')

  • this.$store.dispatch({type:'action type (function name)'},...other parameters)

  • 2.4.5、module

  • Due to the use of a single state tree, the states in the project will be concentrated together, making it difficult to maintain. At this time, the store can be split through modules.

  • After using module, each module has its own state, mutation and other contents, which is convenient for maintenance.

  • How to define

  • const moduleA = {
      state: { ... },
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    const moduleB = {
      state: { ... },
      mutations: { ... },
      actions: { ... }
    }
    const store = new Vuex.Store({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })

    3. Navigation guard (routing guard)

  • 3.2. Global front guard

  • You can register a global beforeEach guard using router.beforeEach:

  • You can register a global beforeEach guard using router.beforeEach:

    router.beforeEach((to, from, next) => {

        console.log(to):

        console.log(from)

        console.log(next)

    })

    analyze:

    // Route pre-guard

    // to page after jump

    // from page before jump

    // next is a function

    // Call next() directly to allow jumps

    // next(false) does not allow jumps

    // next('/index') means jumping to the homepage

    router.beforeEach( ( to , from , next ) => {

        //Before jumping, you can add logical judgment to determine whether to jump to the specified page based on different states.

        // For example, the search page needs to be logged in before you can enter it.

        if(to.meta.isLogin){

        //requires login

        // Determine whether to log in. Write to determine whether to log in.

            next("/")

        }else {

            // No login required

            next()

        }

        // next(false)

        // Determine which pages require login and which pages do not require login

    } )

    //Note: Make sure that the next function is called exactly once in any given navigation guard. It can appear more than once, but only if all logical paths do not overlap, otherwise the hook will never be parsed or an error will be reported.

  • 3.3. Exclusive guard for routing

    You can define beforeEnter guards directly on the route configuration: these guards have the same method parameters as global beforeEnter guards.

    const router = new VueRouter({

      routes: [

        {

          path: '/foo',

          component: Foo,

          beforeEnter: (to, from, next) => {

            // ...

          }

        }

      ]

    })

Guess you like

Origin blog.csdn.net/m0_65849649/article/details/123879430