vuex manage state

Let's analyze the management status of vuex. If you have used the management tree of redux in react, then I think vuex is easy for you to master

If you are still not familiar with what vuex is, then take a look at the official website https://vuex.vuejs.org/zh-cn/intro.html,

Take a look at this picture:

The following example will make it easier to understand:

Take vue's paging component to understand it

1. Create the pagination.vue file.

<template>
    <div class="page-wrap">
      <ul v-show="prePage" class="li-page" v-tap="{methods: goPrePage}">上一页</ul>
      <ul>
        <li v-for="i in showPageBtn" :class="{active: i === currentPage, pointer: i, hover: i && i !== currentPage}"
            v-tap="{methods: goPage, i: i}">
          <a v-if="i" class="notPointer">{{i}}</a>
          <a v-else>···</a>
        </li>
      </ul>
      <ul v-show="nextPage" class="li-page" v-tap="{methods: goNextPage}">下一页</ul>
    </div>
</template>

2. The scope of the component is independent. The parent component communicates to pass data to it through props. The paging component triggers the event defined in the parent component to communicate with the parent component through $emit. Therefore, the default is obtained from the parent component to be displayed. The total number of num is 20 and the limit is 5. Of course, you can also set these two values ​​at will~

let that
export default{
    data(){
      that = this
      return{
        num: 20 ,
        limit: 5
      }
    }
}

3. Calculate several variables, where you can use vue's computed property computed

// The total number of pages totalPage should be equal to the total number to be displayed divided by the number displayed per page, and rounded up, which is easy to understand. 
computed: {
      totalPage () {
        return Math.ceil(that.num / that.limit)
      }
    }
// Offset offset, because clicking on the upper and lower pages and setting page numbers will change the offset variable, and the parent component also needs to use this variable to send an ajax request, so use vuex to store the offset. 
 // pagination.vue 
    computed: {
      offset() {
          return that.$store.state.offset
      }
    }
// The current page currentPage, the current page is a more important variable, showing the number of pages the user is currently on. Knowing the offset and the number displayed on each page, it can be concluded that the current page is the remainder of the two, rounded up, because the number of pages does not start at 0, so 
computed: {
      currentPage() {
        return Math.ceil(that.offset / that.limit) + 1
      }
    }
// Jump event, click the previous page, the next page and the specified page number respectively
 methods: {
      goPage(params) {
        if (params.i === 0 || params.i === that.currentPage) return that.$store.commit('GO_PAGE', (params.i-1) * that.limit) that.$emit('getNew') }, goPrePage() { that.$store.commit('PRE_PAGE', that.limit) that.$emit('getNew') }, goNextPage() { that.$store.commit('NEXT_PAGE', that.limit) that.$emit('getNew') } }

4.vuex part

  • Here is an introduction to the implementation of the vuex part. In the src directory (and the components directory level), create a new store directory, in which the index.js file is passed into mutation to initialize vuex;
// vuex �store/index.js
  import Vue from 'vue'
  import Vuex from 'vuex'
  import mutations from './mutations'

  Vue.use(Vuex);

  const state = {
    offset: 0
  };

  export default new Vuex.Store({
    state,
    mutations
  })
  • mutation-types.js records all event names. In fact, the biggest advantage of this file is that it allows us to manage all vuex methods more intuitively. Its advantages will be highlighted after the project is complicated. When the project is complicated, we may use vuex storage A lot of data and a lot of methods are defined, then mutation-types.js can manage these methods better and more intuitively. This is also a design concept, which is conducive to later maintenance.
    // mutation-types.js
        export const PRE_PAGE = 'PRE_PAGE'
        export const NEXT_PAGE = 'NEXT_PAGE'
        export const GO_PAGE = 'GO_PAGE'

     

  • mutation.js This is the core file of vuex. It registers all the events implemented. We define the methods for clicking the previous page, the next page and jumping to the specified page.
    // mutation.js
      import * as types from './mutation-types'
    
      export default {
         // Pagination previous page 
        [types.PRE_PAGE] (state, offset) {
          state.offset -= offset
        },
        // Pagination to the next page 
        [types.NEXT_PAGE] (state, offset) {
          state.offset += offset
        },
        // Paging jump to the specified page number 
        [types.GO_PAGE] (state, offset) {
          state.offset = offset
        }
      };

    Finally, if you want to monitor the state changes in the store, you can use these two functions, use computed and watch in the page to

computed: {
        initMovies() {
            return this.$store.state.movies;
        },
    },
    watch: {
        initMovies(val) {
            this.movies = val;
        }
    },

 By the way, you can also use this.$store.dispatch to trigger the type in actions, and finally change the state in mutation.js.

For complex projects, using vuex to manage is the best choice.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325122694&siteId=291194637