这篇文章主要介绍“Vue之Pinia状态管理的方法是什么”,在日常操作中,相信很多人在Vue之Pinia状态管理的方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Vue之Pinia状态管理的方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
Pinia开始于大概2019年,其目的是设计一个拥有 组合式 API 的 Vue 状态管理库
目前同时兼容Vue2、Vue3,也并不要求你使用Composition API
Pinia本质上依然是一个状态管理库,用于跨组件、页面进行状态共享
状态管理库是什么?
是一个保存状态和业务逻辑的实体,它会持有为绑定到你组件树的状态和业务逻辑,也就是保存了全局的状态;
它有点像一个永远存在的组件,每个组件都可以读取和写入它;
你可以在你的应用程序中定义任意数量的Store来管理你的状态;
应该在什么时候使用 Store?
一个 Store 应该包含可以在整个应用中访问的数据。这包括在许多地方使用的数据,例如显示在导航栏中的用户信息,以及需要通过页面保存的数据,例如一个非常复杂的多步骤表单。
另一方面,应该避免在 Store 中引入那些原本可以在组件中保存的本地数据,例如,一个元素在页面中的可见性。
安装:npm install pinia
使用 Pinia,即使在小型单页应用中,你也可以获得如下功能:
Devtools 支持
追踪 actions、mutations 的时间线
在组件中展示它们所用到的 Store
让调试更容易的 Time travel
热更新
不必重载页面即可修改 Store
开发时可保持当前的 State
插件:可通过插件扩展 Pinia 功能
为 JS 开发者提供适当的 TypeScript 支持以及自动补全功能。
支持服务端渲染
Store有三个核心概念:
state、getters、actions;
等同于组件的data、computed、methods;
一旦 store 被实例化,你就可以直接在 store 上访问 state、getters 和 actions 中定义的任何属性;
Store 是用 defineStore() 定义的
它需要一个唯一名称,作为第一个参数传递
这个名字 ,也被用作 id ,是必须传入的, Pinia 将用它来连接 store 和 devtools。
返回的函数统一使用useX作为命名方案,这是约定的规范
defineStore() 的第二个参数可接受两类值:Setup 函数或 Option 对象
import { defineStore } from 'pinia'
// 你可以对 `defineStore()` 的返回值进行任意命名,但最好使用 store 的名字,同时以 `use` 开头且以 `Store` 结尾。
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useCounterStore = defineStore('counter', {
// 其他配置...
})
我们也可以传入一个带有 state、actions 与 getters 属性的 Option 对象:
我们可以认为
state 是 store 的数据 (data)
getters 是 store 的计算属性 (computed)
而 actions 则是方法 (methods)
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
与 Vue 组合式 API 的 setup 函数 相似
我们可以传入一个函数,该函数定义了一些响应式属性和方法
并且返回一个带有我们想暴露出去的属性和方法的对象
在 Setup Store 中:
ref()
就是 state
属性
computed()
就是 getters
function()
就是 actions
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
return { count, increment }
})
Store在它被使用之前是不会创建的,我们可以通过调用**useStore()**来使用Store:
<script setup>
import { useCounterStore } from '@/stores/counter'
const store = useCounterStore()
</script>
一旦 store 被实例化,你可以直接访问在 store 的 state、getters 和 actions 中定义的任何属性。
注意Store获取到后不能被解构,那么会失去响应式:
为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()。
state 是 store 的核心部分,因为store是用来帮助我们管理状态的
在 Pinia 中,状态被定义为返回初始状态的函数
import { defineStore } from 'pinia'
export const useCounter = defineStore('counter', {
// 为了完整类型推理,推荐使用箭头函数
state: () => {
return {
// 所有这些属性都将自动推断出它们的类型
counter: 0
}
}
})
读取和写入State:
默认情况下,您可以通过 store 实例访问状态来直接读取和写入状态
const counterStore = useCounter()
counterStore.$reset()
重置State
你可以通过调用 store 上的 $reset() 方法将状态 重置 到其初始值
const counterStore = useCounter()
counterStore.$reset()
变更State
除了用 store.count++
直接改变 store,你还可以调用 $patch
方法
它允许你用一个 state
的对象在同一时间更改多个属性
counterStore.$patch({
counter : 1,
age: 120,
name: 'pack',
})
// 示例文件路径:
// ./src/stores/counter.js
import { defineStore } from 'pinia'
const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
})
Getters 完全等同于 store 的 state 的计算属性
可以通过 defineStore()
中的 getters
属性来定义它们。
推荐使用箭头函数,并且它将接收 state
作为第一个参数
export const useCounter = defineStore('counter', {
state: () => ({
counter: 15
}),
getters: {
doubleCounter: (state) => state.counter * 2
}
})
访问当前store 实例上的 getters
const counterStore = useCounter()
console.log(counterStore.doubleCounter)
Getters中访问当前store实例的其他Getters
我们可以通过 this
,你可以访问到其他任何 getters
getters: {
doubleCount: (state) => state.counter * 2,
// 返回 counter 的值乘以 2 加 1
doubleCountPlusOne() {
return this.doubleCount + 1
}
}
访问其他store实例的Getters
getters: {
otherGetter(state) {
const otherStore = useOtherStore()
return state.localData + otherStore.data
}
}
Getters可以 返回一个函数,该函数可以接受任意参数:
export const useUserListStore = defineStore('main', {
state: () => ({
users: [
{ id: 1, name: 'lisa' },
{ id: 2, name: 'pack' }
]
}),
getters: {
getUserById: (state) => {
return (userId) => {
state.users.find((user) => user.id === userId)
}
}
}
})
在组件中使用:
<template>
<p>User 2: {{ getUserById(2) }}</p>
</template>
<script setup>
import { useUserListStore } from './store'
const userList = useUserListStore()
const { getUserById } = storeToRefs(userList)
</script>
Actions 相当于组件中的 methods。
可以通过 defineStore() 中的 actions 属性来定义,并且它们也是定义业务逻辑的完美选择。
类似 Getters,Actions 也可通过 this 访问整个 store 实例
export const useCounterStore = defineStore('counter', {
state: () => ({
counter: 15
}),
actions: {
increment() {
this.counter++
}
}
})
Actions 中是支持异步操作的,并且我们可以编写异步函数,在函数中使用await
:
Actions 可以像函数或者通常意义上的方法一样被调用:
import { useAuthStore } from './auth-store'
export const useSettingsStore = defineStore('settings', {
state: () => ({
preferences: null,
// ...
}),
actions: {
async fetchUserPreferences() {
const auth = useAuthStore()
if (auth.isAuthenticated) {
this.preferences = await fetchPreferences()
} else {
throw new Error('User must be authenticated')
}
},
},
})
到此,关于“Vue之Pinia状态管理的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/qq_53664443/article/details/129917263