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.

To 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:

import { defineStore, defineActions } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0,
  }),
  actions: {
    increment() {
      this.count++
    },
  },
})

// Define actions separately using `defineActions`
export const useCounterActions = defineActions({
  incrementAsync() {
    // Perform asynchronous operations
    setTimeout(() => {
      // Use `this` to access the store's state and other actions
      this.increment()
    }, 1000)
  },
})

To use an action in a component, you can access it through the $actions property of the store instance:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script>
import { useCounterStore } from './store'

export default {
  setup() {
    const counterStore = useCounterStore()

    const incrementAsync = () => {
      counterStore.$actions.incrementAsync()
    }

    return {
      count: counterStore.count,
      incrementAsync,
    }
  },
}
</script>

In 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.

Note that actions in Pinia are automatically bound to the store instance, so you can access the store's state and other actions using this

vue3 pinia action

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

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