📜  vuex getters - Javascript (1)

📅  最后修改于: 2023-12-03 15:35:39.174000             🧑  作者: Mango

Vuex Getters

Introduction

Vuex is a state-management pattern library for Vue.js applications. It provides a centralized store for managing the state of the application. The Vuex store contains the state, mutations, actions, and getters. Getters are like computed properties and are used to retrieve the state from the Vuex store.

In this article, we will explore Vuex getters and how they can be used in a Vue.js application.

Defining Getters

Getters in Vuex are functions that retrieve data from the store. They are similar to computed properties in Vue.js. You can define a getter in the getters field of a Vuex store.

Here is an example of a getter that retrieves the count of items in the store:

const store = new Vuex.Store({
  state: {
    items: []
  },
  getters: {
    itemCount: state => {
      return state.items.length;
    }
  }
});

In the above code, we define a getters object and add a itemCount getter function to it. The itemCount getter returns the length of the items array in the store.

Using Getters

Getters can be used in Vue.js components using the $store.getters object. You can access a getter by its name. Here is an example of how to use the itemCount getter in a component:

<template>
  <div>
    Number of items: {{ $store.getters.itemCount }}
  </div>
</template>

<script>
export default {
  // ...
};
</script>

In the example above, we use the $store.getters.itemCount getter to retrieve the count of items from the store.

Getters can also be used in other getters. Here is an example of a getter that computes the total price of all items in the store:

const store = new Vuex.Store({
  state: {
    items: [
      {
        name: "Item 1",
        price: 10
      },
      {
        name: "Item 2",
        price: 20
      }
    ]
  },
  getters: {
    itemCount: state => {
      return state.items.length;
    },
    totalPrice: state => {
      return state.items.reduce((total, item) => {
        return total + item.price;
      }, 0);
    }
  }
});

In the above example, we define a totalPrice getter that uses the reduce() method to compute the total price of all items in the items array.

Conclusion

In this article, we explored Vuex getters and how they can be used in a Vue.js application. Getters are used to retrieve data from the Vuex store and are similar to computed properties in Vue.js. They can be defined in the getters field of a Vuex store and accessed using the $store.getters object in Vue.js components. Getters can also be used in other getters to compute complex values.