首頁  >  文章  >  web前端  >  Vue3中怎麼引入Pinia儲存庫並使用

Vue3中怎麼引入Pinia儲存庫並使用

WBOY
WBOY轉載
2023-05-14 19:13:041777瀏覽

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 &#39;vue&#39;;
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 &#39;vue&#39;;
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 &#39;vue&#39;;
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(&#39;hello&#39;, JSON.stringify(state))
})

8.Getter

Getter 完全等同於Store 狀態的計算值。它們可以用 defineStore() 中的 getters 屬性定義。他們接收「狀態」作為第一個參數以鼓勵箭頭函數的使用:(ps:雖然鼓勵但是依然提供了非es6玩家的使用方式內部可以用this代表state)

//store/index.js文件
export const useStore = defineStore(&#39;main&#39;, {
  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(&#39;main&#39;, {
  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儲存庫並使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除