登录
首页 >  文章 >  前端

引入和使用Pinia存储库在Vue3中的操作步骤

来源:亿速云

时间:2024-03-28 23:57:30 416浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《引入和使用Pinia存储库在Vue3中的操作步骤》,正文内容主要涉及到等等,如果你正在学习文章,或者是对文章有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

1.用自己最喜欢的方式安装

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

2.main.js引入

import { createApp } from 'vue'
import App from './App.vue'
 
const app=createApp(App)
import { createPinia } from 'pinia' //引入pinia
app.use(createPinia())
 
app.mount('#app')

3.创建store文件并配置内部的index.js文件

import { defineStore } from 'pinia' //引入pinia
 
//这里官网是单独导出  是可以写成默认导出的  官方的解释为大家一起约定仓库用use打头的单词 固定统一小仓库的名字不易混乱
export const useCar=defineStore("test",{ 
    state: () =>{
        return  ({
            msg:"这是pinia",
            name:"小小",
            age:18
            }) //为了避免出错,返回的值用()包起来
    } 
})

4.组件使用方法


 

5.重置store.$reset()


 

6.群体修改store.$patch,可以将pinia的数据进行同一修改

特点:批量修改但状态只刷新一次


 

7.订阅修改

//可以通过 store 的 $subscribe() 方法查看状态及其变化,通过patch修改状态时就会触发一次
store.$subscribe((mutation, state) => { 
  // 每当它发生变化时,将整个状态持久化到本地存储
  localStorage.setItem('hello', JSON.stringify(state))
})

8.Getter

Getter 完全等同于 Store 状态的 计算值。 它们可以用 defineStore() 中的 getters 属性定义。 他们接收“状态”作为第一个参数以鼓励箭头函数的使用:(ps:虽然鼓励但是依然提供了非es6玩家的使用方式 内部可以用this代表state)

//store/index.js文件
export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  getters: {
    doubleCount: (state) => state.counter * 2,
  },
})
 
//组件中直接使用:  

Double count is {{ store.doubleCount }}

9.Actions

在pinia中没有提供mutaion 因为Actions就够了(它可以异步同步的统一修改状态)之所以提供这个功能 就是为了项目中的公共修改状态的业务统一

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++//1.有this
    },
    randomizeCounter(state) {//2.有参数   想用哪个用哪个
      state.counter = Math.round(100 * Math.random())
    },
    randomizeCounter(state) {
        //异步函数.接口成功赋值
     ajax.hplBaseApi("app/productSelection/categoryRows", {}, "post").then((res) => {
        state.counter = res.data.length
     });
    }
  },
})
 
//组件中的使用:
  setup() {
    const store = useStore()
    store.increment()
    store.randomizeCounter()
  }

理论要掌握,实操不能落!以上关于《引入和使用Pinia存储库在Vue3中的操作步骤》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>