Home > Web Front-end > JS Tutorial > body text

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

不言
Release: 2018-09-01 16:44:02
Original
1830 people have browsed it

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
Copy after login

Then, add:

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

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 }
})
Copy after login

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
Copy after login

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
    }
  }
}
Copy after login

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
    }
  })
}
Copy after login

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'
])
Copy after login

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)
    }
  }
})
Copy after login

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 }]
Copy after login

Getter can also accept other getters as the second parameter:

getters: {
  // ...
  doneTodosCount: (state, getters) => {
    return getters.doneTodos.length
  }
}

store.getters.doneTodosCount // -> 1
Copy after login

Used in components:

computed: {
  doneTodosCount () {
    return this.$store.getters.doneTodosCount
  }
}
Copy after login

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)
  }
}
Copy after login
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Copy after login

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',
      // ...
    ])
  }
}
Copy after login

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

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

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++
    }
  }
})
Copy after login

Call:

store.commit('increment')
Copy after login

Submit payload

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

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

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

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

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')
    }
  }
})
Copy after login

Action is triggered through the store.dispatch method:

store.dispatch('increment')
Copy after login

Execute asynchronous operations inside the action:

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

Pass parameters in object form:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template