vue3中的pinia的使用方法

vue3中的pinia的使用方法

pinia的安装方法

npm install pinia

在src里面新建一个文件夹 store,在store里面新建一个index.js文件 引入pinia

import { createPinia } from 'pinia'
const store = createPinia()
export default store

在main.js里面引入store进行全局挂载

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(router).use(store).mount('#app')

在store里面创建counter.js和shop.js 用于模块化管理
counter.js的代码如下

import { defineStore } from 'pinia'
export const useStore = defineStore('storeId', {
  state: () => {
    return {
      num: 1,
      name: '张三'
    }
  },
  //相当于计算属性 而且具有缓存
  getters: {
    changeNum() {
      return this.num + 100
    }
  },
  actions: {
    //这里可以添加同步和异步的方法
    upNum(val) {
      this.num += val
    }
  }
})

shop.js的代码如下

import { defineStore } from 'pinia'
export const shop = defineStore('shop', {
  state: () => {
    return {
      shopList: ['a', 'b', 'c']
    }
  }
})

在App.vue组件使用store 代码如下

<template>
  <div>
    <h4>{{ changeNum }}</h4>
    <h4>{{ name }}{{ num }}</h4>
    <button @click="btn">点击按钮修改</button>
    <button @click="reset">重置数据</button>
    <button @click="add">action方法</button>
    <hr />
    <h3>shop的数据:{{ shopList }}</h3>
  </div>
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { counter } from './store/counter'
import { shop } from './store/shop'
let countStore = counter()
let shopStore = shop()
let { name, num, changeNum } = storeToRefs(countStore)
let { shopList } = storeToRefs(shopStore)
const btn = () => {
  // name.value = '李四'
  // num.value = 4
  //批量修改state的数据
  countStore.$patch((state) => {
    num.value = 3
    name.value = '王五'
  })
}
//重置数据
const reset = () => {
  countStore.$reset()
}
const add = () => {
  countStore.upNum(2)
}
</script>

Pina和Vuex有什么区别

区别:
1. pinia没有mutations,只有:state、getters、actions
2. pinia分模块不需要modules(之前vuex分模块需要modules)
3. pinia体积更小(性能更好)
4.使用pinia可以在某个组件中直接修改pinia中state的数据

Pinia的持久化存储
Pinia的版本在3以上可以安装pinia-plugin-persistedstate插件作为持久化状态管理

npm i pinia-plugin-persistedstate

在index.js里面的配置引入

import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
store.use(piniaPluginPersistedstate)//挂载

在在store里面 counter.js 使用

  //配置持久化存储变量
  persist: {
    num: 1
  }
### 如何在 Vue 3使用 Pinia 的 Action 方法 为了理解如何在 Vue 3 应用程序中利用 Pinia 进行状态管理和操作,下面提供了一个详细的指南。 #### 安装并配置 Pinia 首先,在项目中安装 `pinia`: ```bash npm install pinia ``` 接着创建一个新的 store 文件夹来放置所有的 Store 类文件。通常会有一个名为 `useMainStore.js` 的文件用于初始化主要的数据存储逻辑[^4]。 #### 创建带有 Actions 的 Store 定义一个包含 actions 属性的对象作为参数传递给 `defineStore()` 函数。actions 是处理异步操作以及可能改变 state 的地方。这里展示了一个简单的计数器示例: ```javascript // src/stores/counterStore.js import { defineStore } from &#39;pinia&#39; export const useCounterStore = defineStore({ id: &#39;counter&#39;, state: () => ({ count: 0, }), actions: { increment() { this.count++ }, async fetchDataFromApi(url) { try { let response = await fetch(url); let data = await response.json(); console.log(data); // 假设 API 返回的是 JSON 数据 // 更新本地状态 this.updateCountBasedOnData(data.someValue); } catch (error) { console.error(&#39;Failed to fetch data:&#39;, error); } }, updateCountBasedOnData(value) { this.count += value; } } }) ``` 上述代码展示了两个 action 方法:一个是同步的 `increment` 来增加计数值;另一个是模拟从网络请求获取数据后更新内部状态的方法 `fetchDataFromApi` 和辅助方法 `updateCountBasedOnData`[^1]。 #### 使用 Store 及其 Actions 要在组件内调用这些 actions,可以这样做: ```html <template> <div> Count is {{ counter }} <button @click="increase">Increment</button> <button @click="loadExternalData">Load Data From Server</button> </div> </template> <script setup> import { ref, computed } from &#39;vue&#39; import { useCounterStore } from &#39;../stores/counterStore&#39; const counterStore = useCounterStore() const counter = computed(() => counterStore.count) function increase() { counterStore.increment() } async function loadExternalData() { await counterStore.fetchDataFromApi(&#39;/api/some-endpoint&#39;) } </script> ``` 这段模板和脚本部分说明了怎样通过按钮点击事件触发相应的 action 调用来修改应用的状态或执行其他业务逻辑[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值