In Vue 3 and Pinia, an action is a function that is used to perform asynchronous operations or modify the state in the store. It is similar to a mutation in Vuex.\n\nTo define an action in a Pinia store, you can use the defineActions function provided by Pinia. Here's an example of how to define and use an action:\n\njavascript\nimport { defineStore, defineActions } from &#x27;pinia&#x27;\n\nexport const useCounterStore = defineStore(&#x27;counter&#x27;, {\n state: () => ({\n count: 0,\n }),\n actions: {\n increment() {\n this.count++\n },\n },\n})\n\n// Define actions separately using `defineActions`\nexport const useCounterActions = defineActions({\n incrementAsync() {\n // Perform asynchronous operations\n setTimeout(() => {\n // Use `this` to access the store&#x27;s state and other actions\n this.increment()\n }, 1000)\n },\n})\n\n\nTo use an action in a component, you can access it through the $actions property of the store instance:\n\nvue\n<template>\n <div>\n <p>Count: {{ count }}</p>\n <button @click="incrementAsync">Increment Async</button>\n </div>\n</template>\n\n<script>\nimport { useCounterStore } from &#x27;./store&#x27;\n\nexport default {\n setup() {\n const counterStore = useCounterStore()\n\n const incrementAsync = () => {\n counterStore.$actions.incrementAsync()\n }\n\n return {\n count: counterStore.count,\n incrementAsync,\n }\n },\n}\n</script>\n\n\nIn this example, the incrementAsync action is called when the button is clicked. It performs an asynchronous operation using setTimeout and then calls the increment action defined in the store to update the count.\n\nNote that actions in Pinia are automatically bound to the store instance, so you can access the store's state and other actions using this.

Vue 3 Pinia Actions: Asynchronous Operations and State Management - Complete Guide

原文地址: https://www.cveoy.top/t/topic/qbFR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录