功能
- 存放网页的全局状态,跨组件或页面共享状态
实现
创建store
- 导入并使用defineStore创建store对象
- defineStore方法接受两个参数:唯一的StoreId,Setup 函数或 Option 对象 Store
- Option Store 类似于 Vue 的选项式 API,需要传入一个带有
state
、actions
与getters
属性的 Option 对象 - Setup Store 类似于 Vue 的组合式 API, 通过传入一个函数,并在其中定义响应属性和方法,最后返回需要暴露的对象
- 导出store对象以供在其它组件中使用
import { defineStore } from 'pinia'//导入
export const useCounterStore = defineStore('counter', () => {//defineStore中传入'counter'作为唯一storeId,并使用Setup对象
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }//返回暴露对象
})
使用store
- 导入store并使用useStore()来创建实例
- 提取实例store的属性
- 为了从 store 中提取属性时保持其响应性,需要使用
storeToRefs()
- 或者直接使用
.
来访问store属性,这种方法也能保证响应性
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const store = useCounterStore()//创建store实例
const { name, doubleCount } = storeToRefs(store)// `name` 和 `doubleCount` 是响应式的 ref
const { increment } = store// 作为 action 的 increment 可以直接解构
setTimeout(() => {
store.increment()
}, 1000)
const doubleValue = computed(() => store.doubleCount)
Last updated on