Vue3.0+vite (5) 之 Pinia

1,165 阅读1分钟

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 如果您熟悉 Composition API,您可能会认为您已经可以通过一个简单的 export const state = reactive({}). 这对于单页应用程序来说是正确的,但如果它是服务器端呈现的,会使您的应用程序暴露于安全漏洞。 但即使在小型单页应用程序中,您也可以从使用 Pinia 中获得很多好处

Pinia特别轻量级,十分简单的编写。将是替换Vuex的工具

首先下载依赖

yarn add pinia
# 或者使用 npm
npm install pinia

main.js 中声明

import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
const store = createPinia()

createApp(App).use(store).mount('#app')

src 中新建文件夹 store 并新建 index.js 文件

import { defineStore } from 'pinia'

// 第一个参数是应用程序中 store 的唯一 id
export const useTestStore = defineStore('Test', {
  // other options...
})

我们在这里定义一个名为useTestStore的store,接下来声明 state,就是要存储的状态

import { defineStore } from 'pinia'

export const useTestStore = defineStore('Test', {
    state:()=>{
        return {
            current:1,
            age:26,
        }
    },
    //类似于computed 可以帮我们去修饰我们的值
    getters:{

    },
    //可以操作异步 和 同步提交state
    actions:{
        setCurrent () {
            this.current++
        },
        changeCurrent(newCurrent){
            this.current = newCurrent
        }
    }
})

声明了两个变量,并且创建了两个方法放入actions

接下来直接调用

<script setup>
import {useTestStore} from '../store'
const Test = useTestStore()

const { current, age } = Test
const Add = () => {
    Test.current++
    //Test.setCurrent()
}
const Jian = ()=>{
  Test.current--
}
const change = ()=>{
  //在他的实例上有$patch方法可以批量修改多个值
  // Test.$patch({
  //     current:200,
  //     age:99
  // })

  //推荐使用函数形式 可以自定义修改逻辑
  // Test.$patch((state)=>{
  //     state.current = 200;
  //     state.age = 40
  // })

  //$state您可以通过将store的属性设置为新对象来替换store的整个状态
  //缺点就是必须修改整个对象的所有属性
  // Test.$state = {
  //     current:10,
  //     age:30
  // }  

  Test.changeCurrent(123)
}
</script>

<template>
  <div>
    pinia:{{ current }}--{{ age }}
    <button @click="Jian">-</button>
    current:{{Test.current}}
    <button @click="Add">+</button>
    age:{{Test.age}}
    <button @click="change">change</button>
  </div>
</template>

<style lang="less" scoped>

</style>

修改state,可以直接对里面的值,直接修改 类似于

Test.current++

或者$patch方法可以批量修改多个值

 Test.$patch({
      current:200,
      age:99
 })

当然也可以在使用 actions 中声明的方法。

对于在Pinia是不允许直接解构是会失去响应性的。上述例子中

const { current, age } = Test
...
<div>
    pinia:{{ current }}--{{ age }}
<div>

按照这样解构,current,与age修改后,不会改变。所以如果想解构,我们可以用storeToRefs

import { storeToRefs } from 'pinia'
const Test = useTestStore()
const { current, age } = storeToRefs(Test)

这样子数据就可以按照预期改变。

getters就相当于计算属性啦,举个简单例子

getters:{
    newAge:(state)=> `我的年龄${state.age}`
},

直接调用

const {newAge} = storeToRefs(Test)

<div>
    {{newAge}}
<div>