提示信息

import { defineStore } from 'pinia'

易辰 已关注

pinia 是一个状态管理库,用于 Vue.js 应用程序,与 Vuex 类似但更轻便,并且有许多优化和改进。

defineStorepinia 中的一个函数,用于定义一个 store。store 是存储应用级别状态和逻辑的地方。

以下是使用 defineStore 的一个基本示例:

  1. import { defineStore } from 'pinia'
  2. export const useStore = defineStore({
  3. // 必须唯一
  4. id: 'main',
  5. // 定义 store 的状态(state)
  6. state: () => ({
  7. counter: 0
  8. }),
  9. // 定义该 store 的行为(actions)
  10. actions: {
  11. increment() {
  12. this.counter++
  13. }
  14. }
  15. })

然后你可以在组件中按需使用此 store:

  1. import { useStore } from '@/stores/main'
  2. export default {
  3. setup() {
  4. const store = useStore()
  5. return {
  6. counter: store.counter,
  7. increment: store.increment
  8. }
  9. }
  10. }

在上述代码中,useStore 是一个自定义函数,当在组件中调用它时,会返回我们定义的 store,你可以访问其状态(state)和行为(actions)。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
易辰 关注 已关注

最近一次登录:2023-11-27 11:14:20   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图