0


Vue3 store+pinia 基本使用

Pinia是什么呢?

pinia是一个状态管理的库,用于跨组件、页面进行状态共享(这和Vuex、Redux一样),用起来像组合式API

Pinia和Vuex有什么区别

1、PInia的最初是为了探索Vuex的下一次迭代会是什么样子,结合了Vuex核心团队讨论中的许多想法;

2、最终,团队意识到Pinia已经实现了Vuex5中大部分内容,所以最终决定用Pinia来替代Vuex;

3、与Vuex相比,Pinia提供了一个更简单的API,具有更少的仪式,提供了Composition-API风格的API

4、更重要的是,与TypeScript一起使用时具有可靠的类型推断支持

与Vuex相比,Pinia很多的优势:

比如mutations不再存在:

1、mutations最初是为devtools集成,但这不在是问题

  1. 他们经常认为是非常冗长

更友好的TpeScipt支持,Vuex之前对Ts的支持很不友好

不在有modules的嵌套结构

你可以灵活使用每一个store,他们是通过扁平化的方式来相互使用的;

不在有命名空间的概念,不在需要记住他们的复杂关系

如何安装使用Pinia

pinia可在创建Vue3项目时勾选,即可创建成功,或者使用命令,便可安装。

npm install pinia
yarn add pinia

2、创建pinia文件

store文件里index.ts

import { defineStore } from 'pinia';

export const useNoiseStatistics = defineStore({
  id: 'counter',

  state: () => ({}),
  getters: {},
  actions: {},
});

在mian.ts里面进行引入

import { createApp } from 'vue'
import App from './App.vue'
import pinia from './stores'

createApp(App).use(pinia).mount('#app')
//定义关于counter的store
import { defineStore } from ‘pinia’

//defineStore 是返回一个函数 函数命名最好有use前缀,根据函数来进行下一步操作
export const useNoiseStatistics = defineStore('counter',{
    state: () => {
        count:99
    }
})

调用pinia,获取pinia状态值,导入Counter.ts,获取Counter.ts里面state.count

<template>
  <div class="home">
    <h2>Home View</h2>
    <h2>count: {{ counterStore.count }}</h2>
  </div>
</template>

<script setup>
  import useNoiseStatistics from '@/stores/counter';

  const counterStore = useNoiseStatistics()

</script>

<style scoped>
</style>

注意:pinia本身是响应式,当改变store的值,页面相应也会进行更改,pinia解构出来的state也是可以调用,但会失去响应式,需要toRef或者pinia自带storeToRefs

<template>
  <div class="home">
    <h2>Home View</h2>
    <h2>count: {{ counterStore.count }}</h2>
    <h2>count: {{ count }}</h2>
    <button @click="incrementCount">count+1</button>
  </div>
</template>

<script setup>
  import { toRefs } from 'vue'
  import { storeToRefs } from 'pinia'
  import useNoiseStatistics from '@/stores/counter';

  const counterStore =useNoiseStatistics()

  // const { count } = toRefs(counterStore)
  const { count } = storeToRefs(counterStore)

  function incrementCount() {
    counterStore.count++
  }

</script>

<style scoped>
</style>

store的核心部分:state,getters,actions

(相当于:data、computed、methods)

认识和定义State

state是store的核心部分,因为store是用来帮助我们管理状态

操作State

1、读取和写入state:

默认情况下,可以通过store实例访问状态来直接读取和写入状态


const counterStore = useNoiseStatistics()

counterStore.counter++
counterStore.name = 'coderWhy'

2、store.$reset() :

可以调用store上的$reset()方法将状态重置到其初始值

const counterStore = useNoiseStatistics()
conterStore.$reset()

3、store.$patch

除了直接用store.counter++修改store,还可以调用$patch

它允许您使用部分‘state’对象同时应该多个修改

const counterStore = useNoiseStatistics()
counterStore.$patch({
    counter:100,
    name:'kobe'
})

4、store.$state

可以通过将其$state属性设置为新对象替换Store的整个状态

conterStore.$state = {
    counter:1,
    name:'why'
}

5、store.$subscribe

可以通过$subscribe监测到store数据变化

//可以通过 store 的 $subscribe() 方法查看状态及其变化,通过patch修改状态时就会触发一次
store.$subscribe((mutation, state) => { 
  // 每当它发生变化时,将整个状态持久化到本地存储
  localStorage.setItem('test', JSON.stringify(state))
})

操作getters

·Getters相当于store的计算属性:
  1. 它们可用defineStore()中的getters属性定义

  2. getters中可以定义接受一个state作为参数的函数

expoer const useNoiseStatistics = defineStore('counter',{
    state: () => {
        counter:100,
        firstname:'kobe'
    },
    getters:{
        doubleCounter(state){
            return state.counter *2
        }
    }
})
·访问Store里getters方法
  1. 访问当前store的getters:
const counterSotre = useNoiseStatistics()
console.log(counterStore.doublCounter)

2.我们可以使用this来访问当前的store实例中getters

expoer const useNoiseStatistics = defineStore('counter',{
    state: () => {
        counter:100,
        firstname:'kobe'
    },
    getters:{
        doubleCounter(state){
            return state.counter *2
        }
        doubleCounterAdd(){
            //this指向store
            return this.doubleCounter +1 
        }
    }
})

3、访问其它store的getters

import useUser from ./user

const userStore = useUser()

expoer const useNoiseStatistics = defineStore('counter',{
    state: () => {
        counter:100,
        firstname:'kobe'
    },
    getters:{
    //调用其它Store
        doubleCounterUser(){
            return this.doubleCounter + userStore.umu
        }
    }
})

4.通过getters可以返回一个函数,可以传参数

expoer const useNoiseStatistics = defineStore('counter',{
    state: () => {
        counter:100,
        firstname:'kobe'
    },
    getters:{
    //调用其它Store
        doubleCounter(state){
            return function (is) {
                return state.id + id
            }
        }
    }
})
const StoreConter = useNoiseStatistics();
//传参
StoreCounter.doublCounter(111)

操作actions

actions 相当于组件中的methods,可以使用defineStore()中的actions属性定义

expoer const useNoiseStatistics = defineStore('counter',{
    state: () => {
        counter:100,
        firstname:'kobe'
    },
    getters:{
    //调用其它Store
        doubleCounter(state){
            return function (is) {
                return state.id + id
            }
        }
    },
    actions:{
        increment(){
            this.counter++
        },
        //传参
        incrementnum(num){
            this.counter += num
        }
    }
})

和getters一样,在action中可以通过this访问整个store实例:

function increment(){
    //调用
    counterStore.increment()
}
function incrementnum(){
    counterStore.increment(10)
}

actions执行异步操作

actions:{
    async fetchHome(){
        //???请求
        const res = await fetch('?????')
        const data = await res.json()
        console.log('data',data)
        return data
    }
}
cosnt counterStore = useNoiseStatistics()

counterStore.fetchHome().then(res => {
    console.log(res)
})

本文转载自: https://blog.csdn.net/m0_62758542/article/details/129004879
版权归原作者 粽子咯 所有, 如有侵权,请联系我们删除。

“Vue3 store+pinia 基本使用”的评论:

还没有评论