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 管理器。