Skip to main content

pinia

基础使用

安装

# vue3
yarn add pinia

# vue2
yarn add pinia @vue/composition-api

引入

TS / JS

// xxxx.ts
import { defineStore } from 'pinia'

// 支持定义类型
interface useCounterStoreState{
count:number
}

// 局部的类型定义
interface UserInfo {
name: string
age: number
}

// 传统定义(类似vuex):
export const storeUser = defineStore('counter', {
//state: ():useCounterStoreState => ({
state: ():useCounterStoreState => ({
count: 0 as number,
userInfo:{} as UserInfo,
}),

// could also be defined as
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++
},
},
})

// 函数式定义(推荐):
// ref() => 对应store
// computed() => 对应getters
// function() => 对应actions
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}

return { count, increment }
})

Vue3

// main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia' // 导入 Pinia
import App from '@/App.vue'

createApp(App)
.use(createPinia()) // 启用 Pinia
.mount('#app')

Vue2

import { storeUser } from '@/stores/xxxx'
import { storeToRefs } from 'pinia'

export default {
setup() {
const counter = storeUser()

counter.count++

// with autocompletion ✨
// 可读性更高
counter.$patch({ count: counter.count + 1 })

// or using an action instead
// 使用更方便
counter.increment()

// state 如果需要解构使用,需要通过storeToRefs导出
// 否则将失去响应性
const { name, doubleCount } = storeToRefs(store)
const { increment } = store

// 导出响应的数据
return { name, doubleCount, increment }
},
}

Store 的使用

定义

  • use开头,并以Store结尾
import { defineStore } from 'pinia'
export const useUserStore = defineStore('user', {})

Option Store

基本与vuex相同,只是去除的mutations

export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},

actions: {
increment() {
this.count++
},
},
})

Setup Store

export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}

return { count, increment }
})

使用

import { useCounterStore } from '@/stores/counter'

export default {
setup() {
const store = useCounterStore()

return {
// 为了能在模板中使用它,你可以返回整个 Store 实例。
store,
}
},
}

约定

  • piniaapi基本以useXxxxxXxx形式命名

API

defineStore

定义一个store

storeToRefs

使用结构的方式获取stroe内部属性,action的结构导出不需要storeToRefs

类型定义

// ...
export const useStore = defineStore('main', {
state: () => {
return {
message: 'Hello World',
// 通过 as 关键字指定 TS 类型
randomMessages: [] as string[],
}
},
// ...
})

// ...
export const useStore = defineStore('main', {
state: () => {
return {
message: 'Hello World',
// 通过尖括号指定 TS 类型
randomMessages: <string[]>[],
}
},
// ...
})

特性

对比Vuex的优点

  • 不再需要使用import进行注册,默认自动注册
  • 不再需要命名空间的嵌套使用,每个store都可以定义一个扁平化的命名