likes
comments
collection
share

Pinia初探

作者站长头像
站长
· 阅读数 8

1.Pinia简介

Pinia也是状态管理工具,相比于vuex

Pinia的优势:

  • vue3、vue2中都可以使用的
  • 抛弃了Mutations的操作,只有state、getters和actions
  • 不需要嵌套模块,符合vue3Composition api
  • 支持typescript
  • 能够让代码更加简介

pinia需要vue环境,在vue官网上

Pinia初探

这里我们使用typescriptPinia直接默认安装就可以的了,主要还是来体验下pinia在数据传递的使用上,带来的体验是否真的便捷。

2.使用Pinia创建一个store:

那么在store文件夹中,主要是做一下几点

  • 定义状态容器和状态
  • 修改状态容器中的state
  • store仓库中的action的使用

工具自动生成的store目录中的内容如下:

stores └─ index.ts

//index.ts 代码如下
import { defineStore } from 'pinia';
export const mainStore = defineStore('main',{
  state:()=>{
    return {
      girlFriend:'yss'
    }
  },
  getters:{},
  actions:{},
})
  • store的创建是通过defineStore定义的
  • defineStore是它的唯一名称

HelloPinia.vuePinia的使用(setup的情况)

// HelloPinia.vue

<script lang="ts">
import {mainStore} from '@/stores/index';
export default {
  setup(){
    const myStore = mainStore();
    return {
      myStore
    };
  }
}
</script>

<template>
  <p>这个是我的女朋友{{myStore.girlFriend}}</p>
</template>

<style scoped>
</style>

运行结果如下:

Pinia初探

3.使用Pinia改变状态数据和注意事项:

下面的要借助与一个计数器的案例,来看下Pinia对于数据的改变

先来看下

store中的counter.ts

//counter.ts

import { ref } from 'vue'
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)

  return { count }
})

HelloCounter.vue组件中修改状态

// HelloCounter.vue
<template>
  <div>
    <p>{{store.count}}</p>
    <button @click="handleClick">修改数据状态</button>
  </div>
</template>

<script setup  lang="ts">
import { useCounterStore } from '@/stores/counter';
  const store = useCounterStore();
  const handleClick = ()=>{
    store.count++;
  };
  
</script>

<style scoped>
</style>

有时候需要,store中定义的状态太多了的,不想要store.count的形式,故而想要对store进行解构

==> const {count} = store 这里需要注意的是,store是一个用reactive包裹的对象。

如果想用解构的方法,那么pinia提供了一个方法storeToRefs,将reactive对象转为普通的对象

====> const {count } =storeToRefs(store);

点击修改数据按钮结果如下图:

Pinia初探

4.Pinia修改数据状态的方式:

a)直接通过store.count++;

b)$patch + 对象:在修改多条数据的情况下

  • //$patch
    const changeStateByPatch = ()=>{
      store.$patch({
        count:stroe.count + 520,
      })
    }
    

c)$patch + 箭头函数

  • const changeStateByPatch = ()=>{
      store.$patch((state)=>{
        state.count ++
      });
    }
    

d)业务逻辑写到store文件的"action"

// counter.ts

import { ref } from 'vue'
import { defineStore } from 'pinia'

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

最后的最后,感谢观看,今天也是爱你的一天哟,莎老板,此篇也只是对官网内容的整理,感受下Pinia带来的体验,更多的可能还需要在实际项目中更好的去感受吧。