← Back to Vue.js Course | Chapter 8: State Management | Lesson 5 of 6

Actions का परिचय

Actions store के methods हैं: state बदलने वाले logic के लिए जगह, async work समेत।

In this page:

  1. Actions
Syntax
markup
actions: {
  actionName(param) {
    this.property = param;
  },
  async fetchData() {
    this.property = await apiCall();
  }
}

Actions

Actions plain functions हैं जिनका this store से bound है। ये async हो सकते हैं, दूसरे actions call कर सकते हैं, और दूसरे stores access कर सकते हैं। Components इन्हें methods की तरह call करते हैं। Mutations actions के अंदर रखना business logic centralize करता है और इसे test करना आसान बनाता है।

Note: Actions async हो सकते हैं और values या promises return कर सकते हैं।

उदाहरण: Actions

markup
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <script src="https://unpkg.com/[email protected]/lib/index.iife.js"></script>
  <script src="https://unpkg.com/pinia@2/dist/pinia.iife.js"></script>
</head>
<body>
<div id="app"><p>{{ todos.items.join(", ") || "empty" }} ({{ todos.loading ? "loading" : "idle" }})</p></div>
<script>
  const useTodos = Pinia.defineStore("todos", {
    state: () => ({ items: [], loading: false }),
    actions: {
      async load() {
        this.loading = true;
        await new Promise((r) => setTimeout(r, 10));   // pretend fetch
        this.items = ["write docs", "ship code"];
        this.loading = false;
      },
      add(text) { this.items.push(text); },
    },
  });
  const app = Vue.createApp({ setup() { return { todos: useTodos() }; } });
  app.use(Pinia.createPinia());
  app.mount("#app");
  const s = useTodos();
  s.load().then(() => { s.add("relax"); Vue.nextTick(() => console.log(document.querySelector("p").textContent)); });
</script>
</body>
</html>

<!-- Output:
Rendered: write docs, ship code, relax (idle)
console: write docs, ship code, relax (idle)
-->
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. components में business logic डालना
  2. async actions await करना भूल जाना
  3. Arrow functions इस्तेमाल करना जो this खो देते हैं
चैप्टर सारांश
  • Actions store methods हैं
  • ये async हो सकते हैं
  • this store को refer करता है
  • ये logic centralize करते हैं
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.