位置: IT常识 - 正文
推荐整理分享Vue状态管理--Pinia使用详解(vue状态管理有哪些),希望有所帮助,仅作参考,欢迎阅读内容。
文章相关热门搜索词:vue状态管理工具有哪些,vue状态管理工具有哪些,vue状态管理pinia,vue状态管理是什么,vue状态管理工具,vue状态管理库 pinia,vue状态管理是什么,vue状态管理库 pinia,内容如对您有帮助,希望把文章链接给更多的朋友!
Pinia开始于大概2019年,最初作为一个实验为Vue重新设计状态管理,让它用起来像组合API。
Pinia本质上依然是一个状态管理的库,用于跨组件、页面进行状态共享(这点和Vuex、Redux一样)。
Pinia(发音为/piːnjʌ/,如英语中的peenya)是最接近piña(西班牙语中的菠萝)的词。
这可能也是Pinia的图标是一个菠萝的原因。
二、Pinia和Vuex的区别Pinia最初是为了探索 Vuex 的下一次迭代会是什么样子,结合了 Vuex 5 核心团队讨论中的许多想法。
最终,团队意识到Pinia已经实现了Vuex5中大部分内容,所以最终决定用Pinia来替代Vuex。
和Vuex相比,Pinia有很多的优势:
mutations不再存在
更友好的TypeScript支持,Vuex之前对TS的支持很不友好
不再有modules的嵌套结构,可以灵活使用每一个store,它们是通过扁平化的方式来相互使用的
不再有命名空间的概念,不需要记住它们的复杂关系
三、Pinia的安装和基本配置3.1 安装Pinia# npm 方式npm install pinia# yarn 方式yarn add pinia3.2 创建一个pinia并且将其传递给应用程序1)新建store文件夹,在此文件夹下新建一个index.jsimport { createPinia } from 'pinia'//创建一个pinia实例const pinia = createPinia()export default pinia2)在main.js中use它import { createApp } from 'vue'import App from './App.vue'import pinia from './stores'createApp(App).use(pinia).mount('#app')完成上述代码后,pinia在项目中就生效了
四、Pinia中的Store4.1 什么是Store?一个Store (如Pinia)是一个实体,它会持有绑定到你组件树的状态和业务逻辑,即保存了全局的状态;
它有点像始终存在,并且每个人都可以读取和写入的组件;
你可以在你的应用程序中定义任意数量的Store来管理你的状态;
Store有三个核心概念: state、getters、actions。
等同于组件的data、computed、methods。
一旦 store 被实例化,你就可以直接在 store 上访问 state、getters 和 actions中定义的任何属性。
4.2 如何定义一个store定义之前需要知道:
store 是使用 defineStore() 定义的
并且它需要一个唯一名称,作为第一个参数传递
这个 唯一名称name,也称为 id,是必要的,Pinia 使用它来将 store 连接到 devtools
返回的函数统一使用useX作为命名方案,这是约定的规范
具体示例:
定义一个counter.js,在里面定义一个store
// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { // 在 Pinia 中,状态被定义为返回初始状态的函数 state: () => ({ count: 99 })})export default useCounter这里有一个注意点,就是defineStore函数的返回值的命名规则:
以use开头,加上传给defineStore函数的第一个参数组成,使用驼峰命名法。
这虽然不是强制,确是一个大家都遵守的规范。
4.3 使用store读取和写入 state:<template> <div class="home"> <h2>Home View</h2> <!-- 2.使用useCounter的实例获取state中的值 --> <h2>count: {{ counterStore.count }}</h2> <h2>count: {{ count }}</h2> </div></template><script setup> import useCounter from '@/stores/counter'; import { storeToRefs } from 'pinia' // 1.直接使用useCounter获取counter这个Store的实例 // 这个函数名称取决于defineStore的返回值 const counterStore = useCounter() // 使用storeToRefs对数据进行结构,让count保持响应式的效果 const { count } = storeToRefs(counterStore) // 3.修改(写入)store counterStore.count++ </script>store在它被使用之前是不会创建的,我们可以通过调用use函数来使用store。
Pinia中可以直接使用store实例去修改state中的数据,非常方便。
注意:
store获取到后不能被解构,因为会让数据失去响应式。
为了从 store中提取属性同时保持其响应式,需要使用storeToRefs()。
4.4 修改state的多种方式1)定义一个关于user的Store
import { defineStore } from 'pinia'const useUser = defineStore("user", { state: () => ({ name: "why", age: 18, level: 100 })})export default useUser2)三种修改state的方式
<script setup> import useUser from '@/stores/user' import { storeToRefs } from 'pinia'; const userStore = useUser() const { name, age, level } = storeToRefs(userStore) function changeState() { // 1.一个个修改状态 // userStore.name = "kobe" // userStore.age = 20 // userStore.level = 200 // 2.一次性修改多个状态 // userStore.$patch({ // name: "james", // age: 35 // }) // 3.替换state为新的对象 const oldState = userStore.$state userStore.$state = { name: "curry", level: 200 } // 下面会返回true console.log(oldState === userStore.$state) }</script>4.5 重置store<script> import useCounter from '@/stores/counter'; const counterStore = useCounter() counterStore.$reset()</script>五、getters的使用Getters相当于Store的计算属性:
它可以用defineStore()中的getters属性定义;
getters中可以定义接受一个state作为参数的函数;
5.1 定义getters// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { state: () => ({ count: 99 }), getters: { // 基本使用 doubleCount(state) { return state.count * 2 }, // 2.一个getter引入另外一个getter doubleCountAddOne() { // this是store实例,可以直接使用另一个getter return this.doubleCount + 1 }, // 3.getters也支持返回一个函数 getFriendById(state) { return function(id) { for (let i = 0; i < state.friends.length; i++) { const friend = state.friends[i] if (friend.id === id) { return friend } } } }, },})export default useCounter5.2 访问getters<template> <div class="home"> <!-- 在模板中使用 --> <h2>doubleCount: {{ counterStore.doubleCount }}</h2> <h2>doubleCountAddOne: {{ counterStore.doubleCountAddOne }}</h2> <h2>friend-111: {{ counterStore.getFriendById(111) }}</h2> </div></template><script setup> import useCounter from '@/stores/counter'; const counterStore = useCounter() // 在js文件中使用 const doubleCount = counterStore.doubleCount; const doubleCountAddOne = counterStore.doubleCountAddOne; const frend = counterStore.getFriendById(111)</script>5.3 getters中获取另一个store中的state/getters数据// 定义关于counter的storeimport { defineStore } from 'pinia'// 引入另一个storeimport useUser from './user'const useCounter = defineStore("counter", { state: () => ({ count: 99, }), getters: { // 4.getters中用到别的store中的数据 showMessage(state) { // 1.获取user信息 const userStore = useUser() // 2.获取自己的信息 // 3.拼接信息(使用另一个store中的数据) return `name:${userStore.name}-count:${state.count}` } }})export default useCounter六、actions的使用actions 相当于组件中的 methods。
可以使用defineStore()中的actions属性定义,并且它们非常适合定义一些业务逻辑。
和getters一样,在action中可以通过this访问整个store实例的所有操作。
6.1 基本定义方式// 定义关于counter的storeimport { defineStore } from 'pinia'const useCounter = defineStore("counter", { state: () => ({ count: 99, }), // 定义actions actions: { increment() { this.count++ }, incrementNum(num) { this.count += num } }})export default useCounter6.2 基本使用方式<template> <div class="home"> <h2>doubleCount: {{ counterStore.count }}</h2> <button @click="changeState">修改state</button> </div></template><script setup> import useCounter from '@/stores/counter'; const counterStore = useCounter() function changeState() { // 可以通过counterStore对象直接使用 // counterStore.increment() counterStore.incrementNum(10) }</script>6.3 Actions中的异步操作import { defineStore } from 'pinia'const useHome = defineStore("home", { state: () => ({ banners: [], recommends: [] }), actions: { async fetchHomeMultidata() { const res = await fetch("http://123.207.32.32:8000/home/multidata") const data = await res.json() //得到数据后直接复制给state this.banners = data.data.banner.list this.recommends = data.data.recommend.list return 'success' } }})export default useHome6.4 调用异步actions方法<script setup> import useHome from '@/stores/home'; const homeStore = useHome() homeStore.fetchHomeMultidata().then(res => { console.log("fetchHomeMultidata的action已经完成了:", res) })</script>上一篇:(HOTA)多目标跟踪MOT指标计算方法(多目标pso)
下一篇:尚融宝28-投资列表展示(尚融宝盈(宁波)投资中心(有限合伙))
友情链接: 武汉网站建设