Installation and use of Vue.js State management mode Vuex (code example)

Source: Internet
Author: User
This article brings you the content is about the Vue.js state management mode VUEX installation and use (code example), there is a certain reference value, the need for friends can refer to, I hope to help you.

Uex is a state management model developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of the application and ensures that the state changes in a predictable manner with appropriate rules.

Installing, using Vuex

First we install Vuex in the Vue.js 2.0 development environment:

NPM Install Vuex--save

Then, add the following in the Main.js:

Import Vuex from ' Vuex ' Vue.use (VUEX); Const STORE = new Vuex. Store ({//store object    state:{        show:false,        count:0    }})

Then, add the Store object when instantiating the Vue object:

New Vue ({  el: ' #app ',  router,  store,//using the store  Template: ' <App/> ', components  : {app}})

Now you can get the state object through store.state and trigger the state change through the Store.commit method:

Store.commit (' increment ') console.log (Store.state.count)//-1

State

Get the Vuex status in the Vue component

The simplest way to read state from a store instance is to return a state in a computed property:

Create a Counter component const Counter = {  Template: ' <p>{{count}}</p> ',  computed: {    count () {      ret Urn this. $store. State.count    }}}  

Mapstate Auxiliary functions

When a component needs to acquire multiple states, it is somewhat repetitive and redundant to declare these states as computed properties. To solve this problem, we can use the Mapstate helper function to help us generate the computed properties:

In a separately built version, the helper function is Vuex.mapstateimport {mapstate} from ' Vuex ' export default {  //...  Computed:mapstate ({    //arrow function to make the code more concise    count:state = State.count,    //Pass string argument ' count ' equals ' state ' and ' state ' . Count '    countalias: ' Count ',    //In order to be able to use ' this ' to get local status, you must use the regular function    countpluslocalstate (state) {      return State.count + This.localcount    }}  )}

We can also pass a string array to mapstate when the name of the computed property of the map is the same as the child node name of State:

Computed:mapstate ([  //Map This.count to Store.state.count  ' count '])

Getter

Similar to computed in Vue, getters is used to calculate state and generate new data (states), just like a computed property, the return value of a getter is cached based on its dependency and is recalculated only if its dependency value has changed.

Getter accepts state as its first argument:

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)}}  )

Access by property

Getter is exposed as a Store.getters object, and you can access these values as attributes:

Store.getters.doneTodos//-[{id:1, Text: ' ... ', done:true}]

Getter can also accept other getters as a second parameter:

Getters: {  //...  Donetodoscount: (state, getters) = {    return getters.doneTodos.length  }}store.getters.donetodoscount//- > 1

Used in Components:

Computed: {  donetodoscount () {    return this. $store. Getters.donetodoscount  }}

Note that the getter caches it as part of the response system of Vue when accessed through attributes.

Access by method

Access by method

You can also implement a getter pass by having the getter return a function. This is useful when you are querying an array in the store:

Getters: {  //...  Gettodobyid: (state) = = (id) + {    return state.todos.find (todo = = = = = id)  }}
Store.getters.getTodoById (2)//-{id:2, text: ' ... ', done:false}

Note that the getter will make the call every time it accesses through the method, without caching the result.

Mapgetters Auxiliary functions

The Mapgetters helper function simply maps the getter in the store to the local computed property:

Import {mapgetters} from ' Vuex ' export default {  //...  Computed: {  //Use the object expansion operator to mix getter into computed object ...    mapgetters ([      ' Donetodoscount ',      ' anothergetter ',      // ...    ])  }}

If you want to take a getter attribute to another name, use the object form:

Mapgetters ({  //Map ' this.donecount ' to ' this. $store. Getters.donetodoscount '  donecount: ' Donetodoscount '})

Mutation

The only way to change the state in the Vuex store is to submit mutation.

Registered:

Const STORE = new Vuex.store ({State  : {    count:1  },  mutations: {    increment (state) {      /// Change status      state.count++    }}  )

Call:

Store.commit (' increment ')

Submit Load (Payload)

You can pass additional parameters to the Store.commit, which is the mutation load (payload):

... mutations: {  increment (state, n) {    State.count + = n  }}
Store.commit (' increment ', 10)

If you submit multiple parameters, you must submit them in the form of an object

... mutations: {  increment (state, payload) {    State.count + = Payload.amount  }}
Store.commit (' increment ', {  amount:10})

Note: The operation in the mutations must be synchronous;

Action

Action is similar to mutation, except that:

    • The Action commits the mutation instead of changing the state directly.

    • An action can contain any asynchronous operation.

Const STORE = new Vuex.store ({State  : {    count:0  },  mutations: {    increment (state) {      state.count++    }  },  actions: {    Increment (context) {      context.commit (' increment ')    }  }})

The Action is triggered by the Store.dispatch method:

Store.dispatch (' increment ')

To perform an asynchronous operation inside an action:

Actions: {  Incrementasync ({commit}) {    setTimeout (() = {      commit (' increment ')    }, +)  } }

Object form pass-through parameter:

Distribution of Store.dispatch (' Incrementasync ', {  amount:10}) in payload form
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.