📜  getter in action vuex - Javascript (1)

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

Getter in Action with Vuex

If you're using Vuex as a state management library in your Vue.js application, you might have heard of "getters." Getters basically work as computed properties, but for Vuex. In this article, we'll take a deeper dive into getters and explore some real-world examples of how to use them effectively.

What Are Getters in Vuex?

Getters are basically a way to retrieve some value from the state in a more organized way. Instead of accessing the state directly, you can define a getter function that takes the state as an argument and returns the desired value based on some logic. You can then use this getter function anywhere in your components just like a computed property.

Here's an example of how to define a getter in Vuex:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, title: "Buy groceries", completed: false },
      { id: 2, title: "Clean the house", completed: true },
      { id: 3, title: "Learn Vuex", completed: false }
    ]
  },
  getters: {
    completedTodos: state => {
      return state.todos.filter(todo => todo.completed);
    }
  }
});

export default store;

In this example, we define a getter called "completedTodos" that filters the todos array and returns only the completed ones.

We can then use this getter in our component like this:

<template>
  <div>
    <h1>Completed Todos:</h1>
    <ul>
      <li v-for="todo in completedTodos" :key="todo.id">
        {{ todo.title }}
      </li>
    </ul>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'completedTodos'
    ])
  }
}
</script>
Real-World Examples

Pagination

When you have a long list of items that needs to be displayed in your component, you often need to implement pagination to avoid overloading the user with too much information.

Using a getter, you can easily calculate the number of pages needed based on the total number of items and the number of items per page:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [
      // ...
    ],
    itemsPerPage: 10
  },
  getters: {
    totalPages: state => {
      return Math.ceil(state.todos.length / state.itemsPerPage);
    }
  }
});

In this example, we define a getter called "totalPages" that calculates the total number of pages based on the number of items in the "todos" array and the number of items per page.

You can then use this getter in your component to render the pagination links based on the total number of pages:

<template>
  <div>
    <!-- render pagination links based on "totalPages" -->
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'totalPages'
    ])
  }
}
</script>

Filtering and Sorting

When you have a list of items that needs to be filtered and sorted based on some criteria, you can use getters to keep your component code cleaner and more organized.

For example, let's say we want to display only the completed todos, sorted by the date they were completed:

// store.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    todos: [
      // ...
    ]
  },
  getters: {
    completedTodosSortedByDate: state => {
      return state.todos
        .filter(todo => todo.completed)
        .sort((a, b) => b.completedAt - a.completedAt);
    }
  }
});

In this example, we define a getter called "completedTodosSortedByDate" that filters the "todos" array based on the completed state and sorts the remaining ones by the "completedAt" property in descending order.

You can then use this getter in your component to display the filtered and sorted list:

<template>
  <div>
    <h1>Completed todos (sorted by date):</h1>
    <ul>
      <li v-for="todo in completedTodosSortedByDate" :key="todo.id">
        {{ todo.title }} - {{ todo.completedAt }}
      </li>
    </ul>
  </div>
</template>

<script>
import { mapGetters } from 'vuex';

export default {
  computed: {
    ...mapGetters([
      'completedTodosSortedByDate'
    ])
  }
}
</script>
Conclusion

Getters are a powerful feature in Vuex that allows you to retrieve values from the state in a more organized and efficient way. By using getters, you can keep your code clean and easy to understand, and avoid duplicating logic across different components.

In this article, we explored some real-world examples of how to use getters effectively, but there are countless other use cases where getters can be useful. To learn more about getters and other features of Vuex, check out the official documentation.