新手入门Pinia

什么是Pinia

Pinia 是 Vue 的专属状态管理库,它允许你跨组件或页面共享状态。它和Vuex作用类似(发音为 /piːnjʌ/),官网

为什么要使用Pinia

与 Vuex 相比,Pinia 不仅提供了一个更简单的 API,也提供了符合组合式 API 风格的 API,最重要的是,搭配 TypeScript 一起使用时有非常可靠的类型推断支持。而且不再有嵌套结构的模块,不再有可命名的模块。

如何使用Pinia

我们使用Vite创建的Vue3项目的时候可以选择使用Pinia,可以打开我们的package.json可以查看
在这里插入图片描述
当然你也可以通过以下方式导入Pinia
yarn add pinia
npm install pinia
在main.js里面有自动创建的pinia的实例

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

const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

Pinia的核心概念

defineStore()用来定义Store

ref() 就是 state 属性
computed() 就是 getters
function() 就是 actions

import {
    
     defineStore } from 'pinia'
export const useStore = defineStore('main', {
    
    
  // 其他配置...
})

defineStore() 的第一个参数要求是一个唯一的名字,第二个参数可接受两类值:Setup 函数或 Option 对象(Vue 的选项式 API 类似)

export const useCounterStore = defineStore('counter', () => {
    
    
  const count = ref(0)
  function increment() {
    
    
    count.value++
  }
  return {
    
     count, increment }
})

const后面的返回值可以任意命名,但是我们最好使用 store 的名字,同时以 use 开头且以 Store 结尾

通过 store 实例访问 state

我们前面已经定义过 useStore,这里可以通过store实例访问

const store = useStore()
store.count++

$reset()方法将 state 重置为初始值

const store = useStore()
store.$reset()

在 pinia 实例上侦听整个 state⭐

当我们实现登录的时候可能会出现登录成功,刷新页面就返回原来的页面,我们可以通过watch监听实现
注意页面也需要导入watch
import { watch} from 'vue'

//实现对整个pinia的本地存储
watch(pinia.state,(state)=>{
    
    
    //监听pinia state的变化 实现了对整个pinia的存
    sessionStorage.setItem('piniaState',JSON.stringify(state))
},{
    
    deep:true})
//运行main.js把pinia数据取出来
pinia.state.value=JSON.parse(sessionStorage.getItem('piniaState')||'{}')

Getter 完全等同于 store 的 state 的计算值。

可以通过 defineStore() 中的 getters 属性来定义它们。推荐使用箭头函数,并且它将接收 state 作为第一个参数:

import {
    
     defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
    
    
  state: () => ({
    
    
    count: 0,
  }),
  getters: {
    
    
    doubleCount(state) {
    
    
      return state.count * 2
    },
  },
})

Action 相当于组件中的 method

import {
    
     useCounterStore } from '../stores/counter'
export default {
    
    
  setup() {
    
    
    const counterStore = useCounterStore()
    return {
    
     counterStore }
  },
  methods: {
    
    
    incrementAndPrint() {
    
    
      this.counterStore.increment()
      console.log('New Count:', this.counterStore.count)
    },
  },
}

以上就是Pinia的基础用法,希望对你有用哦!!!

猜你喜欢

转载自blog.csdn.net/m0_55734030/article/details/128852121