溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Vue3中怎么引入Pinia存儲(chǔ)庫并使用

發(fā)布時(shí)間:2023-03-27 14:13:56 來源:億速云 閱讀:95 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Vue3中怎么引入Pinia存儲(chǔ)庫并使用”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Vue3中怎么引入Pinia存儲(chǔ)庫并使用”吧!

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.創(chuàng)建store文件并配置內(nèi)部的index.js文件

import { defineStore } from 'pinia' //引入pinia
 
//這里官網(wǎng)是單獨(dú)導(dǎo)出  是可以寫成默認(rèn)導(dǎo)出的  官方的解釋為大家一起約定倉庫用use打頭的單詞 固定統(tǒng)一小倉庫的名字不易混亂
export const useCar=defineStore("test",{ 
    state: () =>{
        return  ({
            msg:"這是pinia",
            name:"小小",
            age:18
            }) //為了避免出錯(cuò),返回的值用()包起來
    } 
})

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里面的數(shù)據(jù)
             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里面的數(shù)據(jù)
             console.log(store.name)
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

6.群體修改store.$patch,可以將pinia的數(shù)據(jù)進(jìn)行同一修改

特點(diǎn):批量修改但狀態(tài)只刷新一次

<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里面的數(shù)據(jù)
             console.log(store.name)
        },
        reset(){
             store.$reset() //重置pinia里面的數(shù)據(jù)
             console.log(store.name)
        },
        allModify(){
             store.$patch({
              name:"花花",
              age:20,
            })
        }
    };
    return {
      ...toRefs(state),
      ...methods,
    };
  }
})
</script>

7.訂閱修改

//可以通過 store 的 $subscribe() 方法查看狀態(tài)及其變化,通過patch修改狀態(tài)時(shí)就會(huì)觸發(fā)一次
store.$subscribe((mutation, state) => { 
  // 每當(dāng)它發(fā)生變化時(shí),將整個(gè)狀態(tài)持久化到本地存儲(chǔ)
  localStorage.setItem('hello', JSON.stringify(state))
})

8.Getter

Getter 完全等同于 Store 狀態(tài)的 計(jì)算值。 它們可以用 defineStore() 中的 getters 屬性定義。 他們接收“狀態(tài)”作為第一個(gè)參數(shù)以鼓勵(lì)箭頭函數(shù)的使用:(ps:雖然鼓勵(lì)但是依然提供了非es6玩家的使用方式 內(nèi)部可以用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 因?yàn)锳ctions就夠了(它可以異步同步的統(tǒng)一修改狀態(tài))之所以提供這個(gè)功能 就是為了項(xiàng)目中的公共修改狀態(tài)的業(yè)務(wù)統(tǒng)一

export const useStore = defineStore('main', {
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++//1.有this
    },
    randomizeCounter(state) {//2.有參數(shù)   想用哪個(gè)用哪個(gè)
      state.counter = Math.round(100 * Math.random())
    },
    randomizeCounter(state) {
        //異步函數(shù).接口成功賦值
     ajax.hplBaseApi("app/productSelection/categoryRows", {}, "post").then((res) => {
        state.counter = res.data.length
     });
    }
  },
})
 
//組件中的使用:
  setup() {
    const store = useStore()
    store.increment()
    store.randomizeCounter()
  }

到此,相信大家對(duì)“Vue3中怎么引入Pinia存儲(chǔ)庫并使用”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI