pinia方法调用之Actions

2022-08-06 piniavue3

在vuex中调用方法分为异步调用和同步调用,从我个人来说我认为是非常奇怪的,庆幸的是在pinia中改变了这种设计,所有的方法调用都在Actions中进行,不再区分同步与异步。

# Actions的使用方式

import { defineStore } from 'pinia'

export const useCounterStore = defineStore({
    id: 'counter',
    state: () => ({
        count: 0
    }),
    // 做一些同步、异步的操作,类似于methods,提交state
    actions: {
        increment() {
            this.count++
        }
    }
})

# 1.同步方式

直接调用即可,就像我们上面的使用那样,看看使用方式,直接调用即可

<template>
  <van-button type="primary" @click="Counter.count++">主要按钮{{ Counter.count }}</van-button>
  <van-button type="primary" @click="toPath1">{{ Counter.name }}</van-button>
</template>

<script setup>
import {useCounterStore} from '@/stores/counter.js'
const Counter = useCounterStore()

const toPath1 = () => {
  // Actions同步使用方式,直接调用
  Counter.increment()
}
</script>

# 2.异步方式

结合async,await 修饰使用,和常规方法相比没什么区别

import { defineStore } from 'pinia'
impore api from '@/api/word.js'

export const useCounterStore = defineStore({
    id: 'counter',
    state: () => ({
        count: 0
    }),
    actions: {
        // 和使用常规方法,没有什么不同
        async increment2() {
            const {data} = await 
            this.count = data
        }
    }
})

方法中直接调用即可

<template>
  <van-button type="primary" @click="Counter.count++">主要按钮{{ Counter.count }}</van-button>
  <van-button type="primary" @click="toPath1">{{ Counter.name }}</van-button>
</template>

<script setup>
import {useCounterStore} from '@/stores/counter.js'
const Counter = useCounterStore()

const toPath1 = () => {
  // Actions异步使用方式,也可以直接调用
  Counter.increment2()
}
</script>

# pinia中是如何获取或修改state中的数据的呢?

答案是this调用即可,不需要像vuex通过参数首位占用的方式了。

上次更新: 1 年前