关于vue3 菠萝 Pinia 使用
import { defineStore } from 'pinia'
// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
// 其他配置...
})
defineStore:用来定义类似于一个 新的.vue文件 也可以理解为命名空间 nameScoped:true 模块名 两个参数
defineStore('alerts', {})
alerts: 可以理解为模块名
{}:中间包含 state可以理解为 一个data(){return {
中间是我们定义的数据
a:'你是一个大麻瓜'
}}
state: () => ({ count: 0 }),
面试题:有人会问为什么Pinia中的state是一个箭头函数
个人理解:倘若你用的是vue3+ts 他可以更好的推断 数据中的ts类型
还有一点就是 我们会用到 actions 那么 actions 中间要改变 state 中的状态 需要用到this
箭头函数的this指向 alerts 模块 你要是用了 function 那么 state 属于一个闭包
个人理解哈 有错误评论区可以评论出来
- actions 不能说与 vuex 中的 actions 一致 但是 也差不多 同样支持 一步请求 只不过不需要再去调用mountions 方法 单词可能打错了 见怪莫怪
// 先看 官网 给的 例子
actions: {
increment() { // 定义的 方法 this指向当前 父级作用域 也就是 state 返回出来的 counter
this.counter++ // 可以直接更改 state 中的数据
},
randomizeCounter() {
this.counter = Math.round(100 * Math.random())
},
async getBannerList:{
...(res)=>{
this.bannerList = res.data
}
}
},
getters: {
//对外丢出 轮播图 列表
exportBannerList(){
// 可在此处理 state中的 数据 如 foreach map 等等逻辑
return this.bannerList
}
},
// setup 中 使用
import useAlertsStore form '文件路径'
const store = useAlertsStore()
// 调用bannerList 数据
const list = compound(()=>{
return store.exportBannerList()
})
//调用 actions 中的方法
store.increment()
// 更新 state 中的 数据
store.$pach({ // 可以同时更新 多个
key:value
})