Vue Flux framework-Vuex status manager, vueflux framework-vuex

Source: Internet
Author: User

Vue Flux framework-Vuex status manager, vueflux framework-vuex

Before learning vue, the most important thing is to understand two concepts: "what", what vuex, and why.

What is Vuex?

Vuex is similar to the Redux status manager in React to manage the status of all Vue components.

Why is Vuex used?

When you plan to develop a large single-page application (SPA), multiple view components may depend on the same status. The behavior from different views must be changed to the same status.
In the above cases, you should consider using Vuex, which can extract the sharing status of components and manage them as a global Singleton mode. In this way, no matter where you change the status, the component that uses this status will be notified to make corresponding changes.

The following describes how to use Vuex

A simple Vuex example

This article explains how to install Vuex and how to use Vuex through code.

import Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);const store = new Vuex.Store({  state: {    count: 0  },  mutations: {    increment (state) {      state.count++    }  }})

The preceding is a simple Vuex example. Each Vuex application is a store. The store contains the shared state and the mutations of the changed state (also called the method) in the component.

Note that the state of the store can only be changed through mutations, but not through the store. state. count = 5; directly change (in fact, it can be changed. We do not recommend this. If the state is not changed through mutations, the state will not be synchronized ).

Use the store. commit method to trigger mutations to change the state:

store.commit('increment');console.log(store.state.count) // 1

A simple Vuex application is implemented.

Use Vuex in Vue Components

If you want to update the component data when updating the Vuex status, you can use computed to obtain the state update status.

const Counter = {  template: `<div>{{ count }}</div>`,  computed: {    count () {      return store.state.count;    }  }}

Each store. state is a global state. When Vuex is used, it must be injected into the root component or (entry file.

// Root component import Vue from 'vue '; import Vuex from 'vuex'; vue. use (Vuex); const app = new Vue ({el: '# app', store, components: {Counter}, template: '<div class = "app"> <counter> </div> '})

With this injection mechanism, the sub-component Counter can access through this. $ store:

// Counter component const Counter = {template: '<div >{{ count }}</div>', computed: {count () {return this. $ store. state. count }}}

MapState Function

computed: {  count () {    return this.$store.state.count  }}

The preceding method uses the count calculation attribute to obtain the state. count attribute of the same name. How does one write this method every time it is obtained? You can use the mapState function to simplify this process.

Import {mapState} from 'vuex'; export default {computed: mapState ({count: state => state. count, countAlias: 'Count', // the alias 'Count' is equivalent to state => state. count })}

There are also simpler usage methods:

Computed: mapState (['Count' // ing this. count to store. state. count])

Getters object

If we need to process and compute the state object, as follows:

computed: {  doneTodosCount () {    return this.$store.state.todos.filter(todo => todo.done).length  }}

If such processing is required for multiple components, copy the function from multiple components. This is very inefficient. When this process is changed and the same changes are made in multiple components, it is more difficult to maintain.

The getters object in Vuex allows us to perform centralized processing in store. Getters accepts state as the first parameter:

const store = new Vuex.Store({ state: {  todos: [   { id: 1, text: '...', done: true },   { id: 2, text: '...', done: false }  ] }, getters: {  doneTodos: state => {   return state.todos.filter(todo => todo.done)  } }})

Use the store. getters object in Vue to call:

computed: { doneTodos () {  return this.$store.getters.doneTodos }}

Getter can also accept other getters as the second parameter:

getters: { doneTodos: state => {   return state.todos.filter(todo => todo.done) }, doneTodosCount: (state, getters) => {  return getters.doneTodos.length }}

MapGetters auxiliary functions

Similar to mapState, the code can be simplified. The mapGetters auxiliary function only maps getters in the store to the local computing attribute:

Import {mapGetters} from 'vuex' export default {//... computed: {// use the object expansion operator to mix getters into the computed object... mapGetters (['donetodoscount ', 'anothergetter', //...])}

The above can also be written:

computed: mapGetters([   'doneTodosCount',   'anotherGetter',   // ...  ])

Therefore, there are two auxiliary functions in the computed calculation attribute of Vue:

import { mapState, mapGetters } from 'vuex';export default {  // ...  computed: {    ...mapGetters([ ... ]),    ...mapState([ ... ])  }}

Mutations

As mentioned before, the only way to change the status in the Vuex store is mutations.

Each mutation has an event type and a callback function handler.

To call mutation, you must use the store. commit method to call mutation type:

store.commit('increment')

Payload submission Load

You can also pass the second parameter to store. commit, that is, the payload of mutation:

mutaion: {  increment (state, n) {    state.count += n;  }}store.commit('increment', 10);

Passing in n alone may not meet our business needs. At this time, we can choose to pass in a payload object:

mutation: {  increment (state, payload) {    state.totalPrice += payload.price + payload.count;  }}store.commit({  type: 'increment',  price: 10,  count: 8})

MapMutations Function

No exception. mutations also has the ing function mapMutations, which helps us simplify the code and map the methods in the component to store. commit call using the mapMutations helper function.

Import {mapMutations} from 'vuex' export default {//... methods :{... mapMutations (['credentials' // ing this. increment () is this. $ store. commit ('credentials')]),... mapMutations ({add: 'credentials' // ing this. add () is this. $ store. commit ('credentials ')})}}

Actions

Note that Mutations must be a synchronous function.

If we need asynchronous operations and submit multiple Mutations, Mutations will not meet our needs. At this time, we need Actions.

Actions

Action is similar to mutation. The difference is:

  1. Action submits mutation instead of directly changing the status.
  2. Action can include any asynchronous operation.

Let's register a simple action:

var store = new Vuex.Store({ state: {  count: 0 }, mutations: {  increment: function(state) {   state.count++;  } }, actions: {  increment: function(store) {   store.commit('increment');  } }});

Distribute Action

The Action function accepts a context object that has the same methods and attributes as the store instance. Therefore, you can call context. commit submits a mutation, or uses context. state and context. getters to get the state and getters.

Distribute Action

Action is triggered using the store. dispatch method:

At first glance, it seems that it is more convenient for us to distribute mutation directly? Actually, this is not the case. Do you still remember that mutation must execute this restriction synchronously? Action is not restricted! We can perform asynchronous operations within the action:

actions: { incrementAsync ({ commit }) {  setTimeout(() => {   commit('increment')  }, 1000) }}

Actions supports distribution by the same load and object methods:

// Distribute the store as a load. dispatch ('initmentasync', {amount: 10}) // distribute the store as an object. dispatch ({type: 'initmentasync', amount: 10 })

MapActions

Similarly, actions have corresponding mapActions auxiliary functions.

MapActions

MapActions auxiliary functions are the same as mapMutations in the methods call of components:

Import {mapActions} from 'vuex' export default {//... methods :{... mapActions (['credentials' // ing this. increment () is this. $ store. dispatch ('credentials')]),... mapActions ({add: 'credentials' // ing this. add () is this. $ store. dispatch ('credentials ')})}}

Mutation-types

The official documents on mutation-types are rarely described, but in most projects, the = mutation-types = configuration is indispensable, the Vuex document only describes the four core concepts of state, getters, mutation, and actions. Below I will briefly add the use of mutation-types.

As the name suggests, = mutation-types = is actually the setting of each method in the mutation instance. Generally, before the mutation method, set it in upper case in the mutation-types format, then introduce the application in mutation. Let's take a look at the actual use of the project:

Project Organization Structure


Define the mutation method structure in mutation-types:

// SET_SINGER, SET_SONG is the name of the method to be used in mutation. export const SET_SINGER = 'set _ SINGER 'export const SET_SONG = 'set _ sing'

Import and use in mutation:

import * as types from ',/mutation-types.js'const mutations = {  [types.SET_SINGER](state, singer) {    ....   },  [types.SET_SONG](state, song) {    ....   }}

Conclusion

After reading the vuex on the interpretation of the I believe you have been getting started, now you can look at the specific project to deepen understanding, you can refer to my github a shopping cart example: https://github.com/osjj/vue-shopCart

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.