search
HomeWeb Front-endJS TutorialInstallation and use of Vue.js state management mode Vuex (code example)

The content of this article is about the installation and use of Vue.js state management mode Vuex (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

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

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

Installing and using vuex

First we install vuex in the vue.js 2.0 development environment:

npm install vuex --save

Then, add:

import vuex from 'vuex'
Vue.use(vuex);
const store = new vuex.Store({//store对象
    state:{
        show:false,
        count:0
    }
})

to main.js and then Then, add the store object when instantiating the Vue object:

new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<app></app>',
  components: { App }
})

Now, you can obtain the state object through store.state and trigger state changes through the store.commit method:

store.commit('increment')

console.log(store.state.count) // -> 1

State

Get Vuex state in Vue component

The easiest way to read the state from the store instance is to return a certain state in the calculated property:

// 创建一个 Counter 组件
const Counter = {
  template: `<p>{{ count }}</p>`,
  computed: {
    count () {
      return this.$store.state.count
    }
  }
}

mapState helper function

When a component needs to obtain multiple states, declaring these states as computed properties will be somewhat repetitive and redundant. In order to solve this problem, we can use the mapState auxiliary function to help us generate calculated properties:

// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'

export default {
  // ...
  computed: mapState({
    // 箭头函数可使代码更简练
    count: state => state.count,

    // 传字符串参数 'count' 等同于 `state => state.count`
    countAlias: 'count',

    // 为了能够使用 `this` 获取局部状态,必须使用常规函数
    countPlusLocalState (state) {
      return state.count + this.localCount
    }
  })
}

When the name of the mapped calculated property is the same as the name of the child node of state, we can also pass a string array to mapState :

computed: mapState([
  // 映射 this.count 为 store.state.count
  'count'
])

Getter

Getters are similar to computed in vue. They are used to calculate state and then generate new data (state). Just like calculated properties, the return value of getter will It is cached based on its dependencies and will only be recalculated when its dependency values ​​change.

Getter accepts state as its 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)
    }
  }
})

Accessed via properties

The Getter is exposed as a store.getters object, and you can access these values ​​as properties :

store.getters.doneTodos // -> [{ id: 1, text: '...', done: true }]

Getter can also accept other getters as the 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 getters are used as Vue when accessed through properties Part of a reactive system is caching.

Access via method

Access via method

You can also pass parameters to the getter by letting the getter return a function. It is very useful when you query the array in the store:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

Note that when the getter is accessed through a method, it will be called every time without caching the results.

mapGetters auxiliary function

mapGetters auxiliary function just maps the getters in the store to local calculated properties:

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter',
      // ...
    ])
  }
}

If you want to give a getter property another name, Use object form:

mapGetters({
  // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
  doneCount: 'doneTodosCount'
})

Mutation

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

Registration:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    }
  }
})

Call:

store.commit('increment')

Submit payload

You can pass in additional parameters to store.commit, that is, mutation Payload:

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

If multiple parameters are submitted, they must be submitted in the form of objects

// ...
mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

Note: The operations in mutations must be synchronous;

Action

Action is similar to mutation, except that

  • Action submits a mutation instead of directly changing the state.

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

Action is triggered through the store.dispatch method:

store.dispatch('increment')

Execute asynchronous operations inside the action:

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

Pass parameters in object form:

// 以载荷形式分发
store.dispatch('incrementAsync', {
  amount: 10
})

Related recommendations:

Vue.js of vuex (state management)

How to use Vuex state management

About Vuex’s family bucket status management

The above is the detailed content of Installation and use of Vue.js state management mode Vuex (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!