本文已参与「新人创作礼」活动, 一起开启掘金创作之路。
使用Pinia
安装Pinia
yarn add pinia
//或者用npm
npm install pinia
创建pinia并且将其传递给应用程序
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
//应用程序
import pinia from './store'
createApp(App).use(pinia).mount('#app')
认识Store
- 三个核心概念:state、getters、methods;
- 相当于组件的:data、computed、methods;
- 一旦store被实例化,可以直接在store上访问state、getters 和 actions中定义的任何属性。
使用Store
-
定义一个Store
- 使用defineStore()定义
- 需要一个唯一的name,作为第一个参数传入
-
export const useCounter = defineStore("counter",{ state() { return { counter: 0 } } }
-
- name被用作将store连接到devtools
- 返回的函数统一使用useX作为命名方案【规定】
-
使用定义的Store
-
Store在它被使用之前是不会被创建的,我们可以通过调用use函数来使用Store;
-
import { useCounter } from '@/store/counter' const counterStore = useCounter()
-
-
Store获取到后不能被解构,会失去响应式
-
const { counter } = counterStore//不是响应式 const { counter:counter2 } = toRefs(counterStore)//响应式 const { counter:counter3 } = storeToRefs(counterStore)//是响应式的
-
认识和定义State
- 在Pinia中,状态被定义为返回初始状态的函数
export const useCounter = defineStore("counter",{
state: ()=>({
counter: 0,
name: "why",
age: 18
})
})
操作State
-
读写和写入state
-
//默认情况下,可以通过store实例访问状态来直接读取和写入状态; const counterStore = useCounter() counterStore.counter++ counterStore.name = "coderwhy"
-
-
重置State
-
//可以通过调用store上的 $reset() 方法将状态重置到其初始值 const counterStore = useCounter() counterStore.$reset()
-
-
改变State
-
//除了直接用store.counter++修改store,你可以调用$patch方法 //它允许您使用部分,“state”对象同时应用多个更改 const counterStore = useCounter() counterStore.$patch({ counter: 100, name: "kobe" })
-
-
替换State
-
//你可以通过将其$state 属性设置为新对象来替换Store的整个状态 counterStore.$state = { counter: 1, name: "why" }
-
认识和定义Getters
- Getters 相当于属于Store的计算属性
- 可以用defineStore()中的getters属性定义
- getters可以定义接受一个state作为参数的函数
export const useCounter = defineStore("counter",{
state: ()=> ({
counter: 100,
firstname: "fish"
lastname: "bry",
age: 18
}),
getters: {
doubleCounter: (state) => state.counter *2
doublePlus: (state) => state.counter *2 + 1,
fullname: (state) => state.firstname + state.lastname
}
})
访问Getters
-
访问当前store的Getters:
-
const counterStore = useCounter() console.log(counterStore.doubleCounter)
-
-
Getters中访问自己的其他Getters:
-
//我们可以通过this来访问到当前store实例的所有其他属性 doublePlus: function(state) { return this.doubleCounter +1 }
-
-
访问其他Store的Getters:
-
message: function(state) { const userStore = useUser() return this.fullname + ":" + userStore.nickname }
-
-
Getters也可以返回一个函数,这样就可以接受参数
认识和定义Action
-
相当于组件中的methods
-
可以使用defineStore() 中的actions属性定义,并且它们非常适合定义业务逻辑
-
actions: { increment() { this.counter++ }, randomCounter() { this.counter = Math.random() } }
-
-
和getters一样,在action中可以通过this访问整个store实例的所有操作
Actions执行异步操作
- Actions中是支持异步操作的,并且我们可以编写异步函数,在函数中使用await
action: {
increment(){...},
randomCounter(){...},
async fetchHomeDataAction() {
const res = await fetch("URL")
const data = await res.json()
return data
}
}
const counterStore = useCounter()
counterStore.fetchHomeDataAction().then(res => {
console.log(res)
})