Vue3中怎么引入Pinia存储库并使用

本篇内容主要讲解“Vue3中怎么引入Pinia存储库并使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue3中怎么引入Pinia存储库并使用”吧!

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.组件使用方法

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="modify">修改store.name</button>
</template>
 
<script>
import { defineComponent, ref } from 'vue';
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        modify(){
             store.name = state.testMsg //修改pinia里面的数据
             console.log(store.name)
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

5.重置store.$reset()

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="reset">重置store.name</button>
</template>
 
<script>
import { defineComponent, ref } from 'vue';
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        reset(){
             store.$reset() //重置pinia里面的数据
             console.log(store.name)
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

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

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

<template>
    <h2>{{store.msg}}{{store.name}}{{store.age}}</h2>
    <button @click="modify">修改store.name</button>
    <button @click="reset">重置store.name</button>
    <button @click="allModify">群体修改store.name</button>
</template>
 
<script>
import { defineComponent, ref } from 'vue';
import {
  reactive,
  toRefs,
  onMounted,
  onActivated
} from "vue";
import {useCar} from "../store/index.js" //将之前配置的pinia文件夹中的index.js文件引入
export default defineComponent({
  let store=useCar() //接收
  setup() {
    const state = reactive({
      testMsg: "原始值",
    });
    onMounted(async () => {});
    onActivated(() => {})
    const methods = {
        modify(){
             store.name = state.testMsg //修改pinia里面的数据
             console.log(store.name)
        },
        reset(){
             store.$reset() //重置pinia里面的数据
             console.log(store.name)
        },
        allModify(){
             store.$patch({
              name:"花花",
              age:20,
            })
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

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,
  },
})
 
//组件中直接使用:  <p>Double count is {{ store.doubleCount }}</p>

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()
  }

到此,相信大家对“Vue3中怎么引入Pinia存储库并使用”有了更深的了解,不妨来实际操作一番吧!这里是蜗牛博客网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接