Managing State with Pinia in a Vue Project

Posted by


Vue 프로젝트에서 Pinia를 사용하여 상태 관리를 하는 방법에 대해 자세히 알아보겠습니다. Pinia는 Vue.js 애플리케이션의 상태 관리를 간단하게 처리할 수 있는 상태 관리 라이브러리입니다. Vuex보다 더 간단하고 직관적인 API를 제공하며 TypeScript와의 훌륭한 호환성을 자랑합니다.

Pinia 설치하기

먼저, Pinia를 설치해야 합니다. 프로젝트의 루트 디렉토리에서 아래 명령어를 실행하여 Pinia를 설치합니다.

npm install pinia@latest

Pinia 설정하기

// main.js
import { createPinia } from 'pinia';
import { createApp } from 'vue';

const app = createApp(App);
app.use(createPinia());
app.mount('#app');

상태 정의하기

// store/todos.js
import { defineStore } from 'pinia';

export const useTodos = defineStore({
  id: 'todos',
  state: () => ({
    todos: [],
  }),
  actions: {
    addTodo(text) {
      this.todos.push({ text, completed: false });
    },
    toggleTodo(index) {
      this.todos[index].completed = !this.todos[index].completed;
    },
  },
});

상태 사용하기

// components/TodoList.vue
<template>
  <ul>
    <li v-for="(todo, index) in todos" :key="index">
      <input type="checkbox" v-model="todo.completed" @change="toggleTodo(index)">
      <span :class="{ completed: todo.completed }">{{ todo.text }}</span>
    </li>
  </ul>
</template>

<script>
import { useTodos } from '@/store/todos';

export default {
  setup() {
    const todos = useTodos((store) => store.todos);
    const { toggleTodo } = useTodos();

    return { todos, toggleTodo };
  },
};
</script>

위와 같이 상태를 정의하고 사용할 수 있습니다. Pinia는 Vue Composition API와 함께 사용할 때 최적의 성능을 발휘하며, 간단하고 직관적인 방법으로 상태를 관리할 수 있습니다. Vuex에 비해 문법이 더 직관적이며, TypeScript와의 호환성도 우수하므로 Vue 프로젝트에서 Pinia를 사용하여 상태 관리를 해보세요.

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@kimmarcus.b.9959
14 days ago

담백한 설명 좋네요. 감사합니다.

1
0
Would love your thoughts, please comment.x
()
x