您的位置:首页 > 娱乐 > 八卦 > 【piania 的用法】

【piania 的用法】

2024/10/5 14:37:40 来源:https://blog.csdn.net/weixin_46252229/article/details/140151595  浏览:    关键词:【piania 的用法】

piania 的用法

  • 定义store
  • 建议使用箭头函数
  • TypeScript
  • 插件扩展
    • 1、全局添加对象

定义store

import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
// pinia 以函数的形式暴露出去
export const useCounterStore = defineStore('counter', () => {// 1、ref 相当于 stateconst count = ref(1)// 2、computed 相当于 getterconst doubleCount = computed(() => count.value * 2)// 3、function 相当于 actionfunction increment():void {count.value++}return { count, doubleCount, increment }
})

使用

import { useCounterStore } from '@/stores/counter'const counter = useCounterStore()

建议使用箭头函数

import { defineStore } from 'pinia'const useStore = defineStore('storeId', {// 为了完整类型推理,推荐使用箭头函数state: () => {return {// 所有这些属性都将自动推断出它们的类型count: 0,name: 'Eduardo',isAdmin: true,items: [],hasChanged: true,}},
})

TypeScript

// 定义接口
interface State {userList: UserInfo[]user: UserInfo | null
}const useStore = defineStore('storeId', {state: (): State => {return {userList: [],user: null,}},
})interface UserInfo {name: stringage: number
}

插件扩展

1、全局添加对象

import { createPinia } from 'pinia'// 创建的每个 store 中都会添加一个名为 `secret` 的属性。
// 在安装此插件后,插件可以保存在不同的文件中
function SecretPiniaPlugin() {return { secret: 'the cake is a lie' }
}const pinia = createPinia()
// 将该插件交给 Pinia
pinia.use(SecretPiniaPlugin)// 在另一个文件中
const store = useStore()
store.secret // 'the cake is a lie'

这对添加全局对象很有用,如路由器、modal 或 toast 管理器。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com