pinia的使用总结


一、定义一个store

  • 安装pinia yarn add pinia
  • 引入pinia
//main.ts
import { createPinia } from 'pinia'
app.use(createPinia())
  • 定义一个store
    defineStore() 需要一个唯一的名称,作为第一个参数传递
import { defineStore } from 'pinia'

// useStore could be anything like useUser, useCart
// the first argument is a unique id of the store across your application
export const useStore = defineStore('main', {
  // other options...
})

  • 使用store
import { useCounterStore } from '@/stores/counter'
const store =useCounterStore()
//获取state 方法一
const doubleValue=computed(() => store.doubleCount),
//获取state 结构state 方法二
const { name, doubleCount } = storeToRefs(store)

//修改state数据 方法一
store.counter++
//修改多个数据 方法二
store.$patch({
  name:"xxx",
  doubleCount+=1
})
//修改多个数据 方法三
store.$patch(state=>{
  state.name='xxx'
  state.doubleCount+=1
  state.arr.push(2)
})
//修改多个数据 方法四
//将操作封装到一个函数里面然后调用即可
store.changeState()

二、核心概念

1.state

定义一个state

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return {
     count: 0 as number  //可以指定数据类型
      }
  },   //必须是一个箭头函数否则类型不会推导
  // could also be defined as
  // state: () => ({ count: 0 })
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

组件内使用state

import { useCounterStore } from '@/stores/counter'
const store =useCounterStore()
//获取state 方法一
const doubleValue=computed(() => store.doubleCount),
//获取state 结构state 方法二
const { name, doubleCount } = storeToRefs(store)

//修改state数据 方法一
store.counter++
//修改多个数据 方法二
store.$patch({
  name:"xxx",
  doubleCount+=1
})
//修改多个数据 方法三
store.$patch(state=>{
  state.name='xxx'
  state.doubleCount+=1
  state.arr.push(2)
})
//修改多个数据 方法四
//将操作封装到一个函数里面然后调用即可
store.changeState()
//您可以通过调用store 上的方法将状态重置为其初始值:$reset()
store.$reset()

2.getters

接受state参数,鼓励使用箭头函数
定义一个getters

  getters: {
   //方法一 使用state获取数据
    doubleCount: (state) => state.counter * 2,
    },
    //方法二使用this获取数据,类型推导不出来必须手动指定返回值类型
    
    //如果要访问其他的getters必须使用this这种写法
    doublePlusOne(): number {
      // autocompletion and typings for the whole store ✨
      return this.doubleCount + 1
    },

   //方法三 支持payload 返回值为一个函数就可以解决payload的问题
    getUserById (state) {
      return (userId) => state.users.find((user) => user.id === userId)
    },
   //方法四接受其他store里面的getters 
    otherGetter(state) {
      const otherStore = useOtherStore()   //直接使用其他store就可以调用了
      return state.localData + otherStore.data
  },

组件内使用getters

const  doubleCount=computed(()=>{
    return store.doubleCount
}) 

3.action

可以接受一个payload参数
定义一个action

  actions: {
    //支持自定义参数 payload
    increment(num:number) {
      this.count+=num
    },
    //支持使用$patch做批量更新数据
    changeState(){
      this.$patch(state=>{
        state.name='xxx'
        state.doubleCount+=1
        state.arr.push(2)
    })
   },
    //使用其他容器的actions
    async fetchUserPreferences() {
      const auth = useAuthStore()    //直接把其他容器加载进来使用就可以了
      if (auth.isAuthenticated) {
        this.preferences = await fetchPreferences()
      } else {
        throw new Error('User must be authenticated')
      }
    },
  },

组件内使用action

store.increment(10)
store.changeState()

三、函数式写法

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

  return { count, increment }
})

四、插件

Pinia 插件是一个函数,可以选择返回要添加到商店的属性。它需要一个可选参数,一个context:

import { createPinia } from 'pinia'

// add a property named `secret` to every store that is created after this plugin is installed
// this could be in a different file
function SecretPiniaPlugin() {
  return { secret: 'the cake is a lie' }
}

const pinia = createPinia()
// give the plugin to pinia
pinia.use(SecretPiniaPlugin)

// in another file
const store = useStore()
store.secret // 'the cake is a lie'

五、与vuex的区别

  • mutations no longer exist. They were very often perceived as extremely verbose. They initially brought devtools integration but that is no longer an issue. //没有mutation
  • No need to create custom complex wrappers to support TypeScript, everything is typed and the API is designed in a way to leverage TS type inference as much as possible. //很好的支持typescript
    No more magic strings to inject, import the functions, call them, enjoy autocompletion!
  • No need to dynamically add stores, they are all dynamic by default and you won’t even notice. Note you can still manually use a store to register it whenever you want but because it is automatic you don’t need to worry about it.
  • No more nested structuring of modules. You can still nest stores implicitly by importing and using a store inside another but Pinia offers a flat structuring by design while still enabling ways of cross composition among stores. You can even have circular dependencies of stores. //没有module了
  • No namespaced modules. Given the flat architecture of stores, “namespacing” stores is inherent to how they are defined and you could say all stores are namespaced. //没有命名空间
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Vue 3 中可以使用 PWA 相关库 Pinia 来管理状态。 首先,需要在 Vue 3 中安装 Pinia: ``` npm install @vueuse/pinia ``` 然后,在项目中使用 Pinia,可以在 main.js 中进行配置: ``` import { createApp } from 'vue' import App from './App.vue' import { createPinia } from '@vueuse/pinia' const pinia = createPinia() const app = createApp(App) app.use(pinia) app.mount('#app') ``` 在组件中使用 Pinia,可以用 `setup()` 函数进行配置: ``` import { useStore } from '@vueuse/pinia' export default { setup() { const store = useStore('example') return { count: store.state.count, increment() { store.commit('increment') } } } } ``` 然后就可以在组件中使用 `count` 和 `increment()` 了。 ### 回答2: Pinia 是 Vue 3 生态系统中的状态管理库,它是一个为 Vue 3 设计的简单但功能强大的状态管理解决方案。使用 Pinia 可以更好地管理和组织 Vue 3 应用程序的状态。 在 Vue 3 中,使用 Pinia 非常简单。首先,我们需要安装 Pinia: npm install pinia 然后,在我们的应用程序的入口文件中导入并创建一个 Pinia 实例: import { createPinia } from 'pinia' import { createApp } from 'vue' const pinia = createPinia() const app = createApp(App) app.use(pinia) app.mount('#app') 现在,我们可以在我们的组件中使用状态管理了。我们可以使用 defineStore 函数来定义一个存储,该存储将包含我们的状态和一些操作。例如,我们可以定义一个名为 "counter" 的存储: import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ }, decrement() { this.count-- } } }) 然后,在我们的组件中使用该存储: <template> <div> <p>Count: {{ count }}</p> <button @click="increment">Increment</button> <button @click="decrement">Decrement</button> </div> </template> <script> import { useCounterStore } from './store' export default { setup() { const counter = useCounterStore() return { count: counter.count, increment: counter.increment, decrement: counter.decrement } } } </script> 现在,我们可以在组件中使用 count 变量来访问存储中的计数,并通过点击按钮来增加或减少计数。 总结起来,Vue 3 中使用 Pinia 只需几步即可轻松实现状态管理。首先,我们需要安装 Pinia 并在入口文件中创建 Pinia 实例。然后,我们使用 defineStore 函数定义我们的存储,并在组件中使用该存储。这使得我们可以使用存储中的状态和操作来管理和共享应用程序的状态。 ### 回答3: Vue 3是一种用于构建用户界面的现代JavaScript框架,而Pinia是使用Vue 3生态系统中的新状态管理库。 Vue 3中使用Pinia主要可以提供更好的状态管理和数据流解决方案。 Pinia的主要特点之一是它是基于Vue 3的新响应式系统创建的。与传统的Vue 2响应式系统相比,它具有更高的性能和更好的内存管理。此外,Pinia还提供了更好的组织代码的结构,使项目更加可维护和可扩展。 在Vue 3中使用Pinia的第一步是安装Pinia插件。可以通过使用npm或yarn命令来安装它。安装完成后,需要在应用程序的入口文件中注册Pinia插件。 接下来,可以在Vue组件中使用Pinia状态。首先,需要导入createPinia函数并使用它创建一个Pinia实例。然后,可以使用该实例的`useStore`函数来创建和使用Pinia存储。 Pinia存储是一个类,它通过定义状态和方法来跟踪和管理应用程序的数据。可以在存储类中定义一些公共状态、计算属性和方法。存储类可以在Vue组件中实例化,并通过Vue组件的provide/inject机制进行共享。 另外,在Vue 3中,可以使用defineProps和defineEmits函数来定义组件的输入和输出。这些函数使得组件的属性和事件变得类型安全和更易于维护。 总之,Vue 3和Pinia之间的结合为Vue开发者提供了更好的状态管理和数据流解决方案。通过使用Pinia,可以更好地组织代码并提高应用程序的性能和可维护性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值