6、Vue 3 Pinia 使用实录:Action

作者: 温新

图书: 【Vue 3 Pinia 使用实录】

阅读: 221

时间: 2024-10-18 10:25:33

嗨,我是温新

Actions 相当于 methods,使用 defineStore 中的 actions 属性定义。它适合对业务逻辑的处理。

1、定义 action

src/stores/info.ts

import { defineStore } from "pinia";

const useInfoStore = defineStore('info', () => {
    // action 就是方法,就这样去理解
    const getRandomNumber = () => {
        return Math.floor(Math.random() * 100)
    }

    return {
        getRandomNumber
    }
})

export default useInfoStore
2、使用 action

src/App.vue

<template>
  <h3>Vue 3 Pinia 使用实录</h3>
  <div class="main">
	  <h2>{{  getRandomNumber() }}</h2>
  </div>
  
</template>

<script setup lang="ts">
	import  useInfoStore  from "@/stores/info.ts";
	import { storeToRefs } from 'pinia'

	const infoStore = useInfoStore()
	const { getRandomNumber } = infoStore;
</script>
请登录后再评论