欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue3中使用Pinia的方法詳細(xì)介紹

 更新時(shí)間:2024年01月17日 11:01:33   作者:九仞山  
這篇文章主要給大家介紹了關(guān)于Vue3中使用Pinia的相關(guān)資料,pinia是一個(gè)用于vue的狀態(tài)管理庫(kù),類似于vuex,是vue的另一種狀態(tài)管理工具,文中介紹的非常詳細(xì),需要的朋友可以參考下

Pinia介紹

Pinia是一個(gè)專門為Vue.js設(shè)計(jì)的狀態(tài)管理庫(kù),它提供了一種簡(jiǎn)單和直觀的方式來管理應(yīng)用程序的狀態(tài)。在使用Pinia時(shí),可以輕松地創(chuàng)建定義狀態(tài)的存儲(chǔ),然后將其與Vue組件綁定,使它們能夠使用該狀態(tài)。和上一個(gè)博客提到的Vuex相比,Pinia 更加簡(jiǎn)單易用,體積更小,同時(shí)具有更好的 TypeScript 支持和插件系統(tǒng)。

在Vue.js的官網(wǎng)中,我們可以看到Pinia目前已經(jīng)取代Vuex,成為Vue生態(tài)系統(tǒng)的一部分。

安裝和配置Pinia

安裝和配置Pinia非常簡(jiǎn)單,像其他Vue插件一樣,Pinia需要通過yarn或npm進(jìn)行安裝并且與Vue應(yīng)用程序進(jìn)行綁定,可以使用以下命令進(jìn)行安裝:

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

在安裝完P(guān)inia包之后,需要在main.ts文件中導(dǎo)入createPinia函數(shù)并將Pinia插件與Vue應(yīng)用程序綁定,如下所示:

import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';

const app = createApp(App);

const pinia = createPinia();
app.use(pinia);

app.mount('#app');

使用 createPinia() 函數(shù)創(chuàng)建并初始化Pinia插件實(shí)例,將其與Vue應(yīng)用程序綁定使用app.use(pinia)。至此,我們就可以使用Pinia來管理Vue應(yīng)用程序的狀態(tài)了。

Pinia的核心

Store

Store是 Pinia 中管理狀態(tài)的核心概念。它相當(dāng)于一個(gè) Vue 組件中的狀態(tài),但是 Store是一個(gè)獨(dú)立的模塊。

Store 是用 defineStore() 定義的,它的第一個(gè)參數(shù)要求是一個(gè)獨(dú)一無二的名字,這個(gè)名字 ,也被用作 id ,是必須傳入的, Pinia 將用它來連接 store 和 devtools。為了養(yǎng)成習(xí)慣性的用法,將返回的函數(shù)命名為 use… 是一個(gè)符合組合式函數(shù)風(fēng)格的約定。

defineStore() 的第二個(gè)參數(shù)可接受兩類值:Setup 函數(shù)或 Option 對(duì)象。

定義Store的示例代碼:

import { defineStore } from 'pinia'

// 你可以對(duì) `defineStore()` 的返回值進(jìn)行任意命名,但最好使用 store 的名字,同時(shí)以 `use` 開頭且以 `Store` 結(jié)尾。(比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一個(gè)參數(shù)是你的應(yīng)用中 Store 的唯一 ID。
export const useAlertsStore = defineStore('alerts', {
  // 其他配置...
})

State

State 是 store 中存儲(chǔ)數(shù)據(jù)的地方。通過定義 State,可以在 store 的任何位置訪問和修改數(shù)據(jù)。

在 Pinia 中,state 被定義為一個(gè)返回初始狀態(tài)的函數(shù)。這使得 Pinia 可以同時(shí)支持服務(wù)端和客戶端。
定義State的示例代碼如下:

import { defineStore } from 'pinia'

const useStore = defineStore('storeId', {
  // 為了完整類型推理,推薦使用箭頭函數(shù)
  state: () => {
    return {
      // 所有這些屬性都將自動(dòng)推斷出它們的類型
      count: 0,
      name: 'Eduardo',
      isAdmin: true,
      items: [],
      hasChanged: true,
    }
  },
})

Getter

Getter 用來獲取從 state 派生的數(shù)據(jù),類似于 Vue 組件中的 computed 計(jì)算屬性??梢酝ㄟ^ defineStore() 中的 getters 屬性來定義它們。推薦使用箭頭函數(shù),并且它將接收 state 作為第一個(gè)參數(shù):

export const useStore = defineStore('main', {
  state: () => ({
    count: 0,
  }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
})

Action

Action 相當(dāng)于組件中的 方法。它們可以通過 defineStore() 中的 actions 屬性來定義;Action 是一種將異步操作封裝在 store中的方式,它是一個(gè)可以被調(diào)用的函數(shù),也可以接收參數(shù)并修改 store 中的狀態(tài)。 Action應(yīng)該始終是同步的,并返回一個(gè) Promise 對(duì)象,以便在處理異步操作時(shí)能夠很好地處理結(jié)果。

Pinia 中的 Action 由 defineStore 創(chuàng)建,可以通過在 actions 中定義它們來使用它們。例如,下面是一個(gè) store 中的 Action 定義:

import { defineStore } from 'pinia'

export const myStore = defineStore('myStore',{ 
  state: () => ({
    message: 'Hello',
  }),
  actions: {
    async fetchMessage() {
      const response = await fetch('http://127.0.0.1:5173/message')
      const data = await response.json()
      this.message = data.message
    },
  },
})

在上面的示例中,我們?yōu)?myStore 定義了一個(gè) Action , fetchMessage() ,它會(huì)從后臺(tái) API 中獲取數(shù)據(jù),并更新 store 中的狀態(tài)。然后,我們可以從組件或其他 Action 中調(diào)用該 Action :

import { useStore } from 'pinia'

export default {
  setup() {
    const store = useStore('myStore')

    function handleClick() {
      store.fetchMessage()
    }

    return {
      handleClick,
    }
  },
}

在上面的代碼中,我們?cè)诮M件中使用 useStore 鉤子來獲取 store 實(shí)例,然后將其傳遞給 fetchMessage() 方法。該方法將從應(yīng)用程序的后臺(tái)獲取數(shù)據(jù),并更新存儲(chǔ)器中的狀態(tài)。最后,公開了一個(gè) handleClick() 方法,以便組件可以調(diào)用它并觸發(fā) Action 。

創(chuàng)建和使用Pinia

創(chuàng)建Pinia

前面我們已經(jīng)安裝和配置好了Pinia,在創(chuàng)建Pinia之前,為了代碼的統(tǒng)一管理和可維護(hù)性,我們依然先創(chuàng)建一個(gè)store文件夾,然后在來創(chuàng)建相關(guān)的Pinia,具體步驟如下

  • 在src文件夾下新建store文件夾,后面所有涉及需要Pinia進(jìn)行狀態(tài)管理的代碼都放在該文件夾下
  • 在store文件夾下新建movieListStore.js文件,創(chuàng)建完成后,打開該文件
  • 在movieListStore.js文件中引入Pinia中的defineStore 方法
import { defineStore } from 'pinia'
  • 創(chuàng)建defineStore 對(duì)象,定義一個(gè)useMovieListStore用于接收defineStore創(chuàng)建的對(duì)象,并將其通過export default 導(dǎo)出
 const useMovieListStore = defineStore('movie',{ 
  state: () => ({
    isShow: true,
    movies: [],
  }),
  getters: {
    getIsShow() {
      return this.isShow
    },
    getMovies() {
      return this.movies
    },
  },
  actions: {
    setIsShow(value) {
      this.isShow = value
    },
    async fetchMovies() {
      const response = await fetch('https://api.movies.com/movies')
      const data = await response.json()
      this.movies = data
    },
  },
})
export default useMovieListStore 

在上面的代碼中,我們使用action定義了兩個(gè)方法,一個(gè)同步方法setIsShow,
一個(gè)異步方法 fetchMovies
注意:這里需要注意,官方建議我們?cè)诙x鉤子函數(shù)時(shí),建議使用use開頭Store結(jié)尾的命名方式來對(duì)上面創(chuàng)建的對(duì)象進(jìn)行命名,如上面的useMovieListStore

使用Pinia

前面我們已經(jīng)創(chuàng)建好了Pinia,接下來,我們就可以在組件中使用了。

在Vue組件中使用store,我們需要通過 useStore() 函數(shù)訪問store的實(shí)例。

在Vue組件中使用Pinia的步驟如下

  • 先使用 import 引入Pinia 中的 useStore
import { useStore } from 'pinia'
  • 創(chuàng)建useStore對(duì)象
const store = useStore('movie')
  • 在需要獲取狀態(tài)的地方通過上面定義的store.getIsShow()獲取狀態(tài)
return {
   isShow: store.getIsShow(),
}

Menu.vue中完整的示例代碼如下:

<template>
  <nav>
    <ul>
      <li v-show="isShow">{{ $route.name }} </li>
      <li><router-link to="/">Home</router-link></li>
      <li><router-link to="/movies">Movies</router-link></li>
    </ul>
  </nav>
</template>

<script>
import { defineComponent } from 'vue'
import { useStore } from 'pinia'

export default defineComponent({
  name: 'Menu',

  setup() {
    const store = useStore('movie')

    return {
      isShow: store.getIsShow(),
    }
  },
})
</script>

Pinia的Option Store方式定義 Store

Option Store方式定義 Store 與 Vue 的選項(xiàng)式 API 類似,我們通過傳入一個(gè)帶有 state、actions 與 getters 屬性的 Option 對(duì)象來定義,示例代碼如下:

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0 }),
  getters: {
    double: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

我們可以認(rèn)為 state 是 store 的數(shù)據(jù) (data),getters 是 store 的計(jì)算屬性 (computed),而 actions 則是方法 (methods)。

Pinia的Setup Store方式定義 Store

Setup Store與Option Store稍有不同,它與 Vue 組合式 API 的 setup 函數(shù) 相似,我們通過傳入一個(gè)函數(shù),該函數(shù)定義了一些響應(yīng)式屬性和方法,并且返回一個(gè)帶有我們想暴露出去的屬性和方法的對(duì)象。示例代碼如下:

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  function increment() {
    count.value++
  }

  return { count, increment }
})

在 Setup Store 中:

  • ref() 就是 state 屬性
  • computed() 就是 getters
  • function() 就是 actions

示例代碼

下面通過一個(gè)實(shí)例來完整的說明Pinia狀態(tài)管理的使用方法,現(xiàn)在要實(shí)現(xiàn)如下效果:

現(xiàn)在頁面上需要完成兩個(gè)功能,一個(gè)功能是通過監(jiān)聽isShow的值,來控制不同頁面跳轉(zhuǎn)時(shí),底部菜單欄button的顯示和隱藏;另一個(gè)功能是通過一個(gè)函數(shù)連接網(wǎng)絡(luò)獲取電影列表,并在詳情頁展示出來

在選項(xiàng)式API中,實(shí)現(xiàn)代碼如下:

  • main.js中的代碼
// main.js

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import { movieStore } from './store/movieStore'

const app = createApp(App)

app.use(createPinia())
app.use(movieStore)

app.mount('#app')
  • store文件夾下movieStore.js中的代碼
// store/movieStore.js

import { defineStore } from 'pinia'

export const useMovieListStore = defineStore('movie',{ 
  state: () => ({
    isShow: true,
    movies: [],
  }),
  getters: {
    getIsShow() {
      return this.isShow
    },
    getMovies() {
      return this.movies
    },
  },
  actions: {
    setIsShow(value) {
      this.isShow = value
    },
    async fetchMovies() {
      const response = await fetch('https://api.movies.com/movies')
      const data = await response.json()
      this.movies = data
    },
  },
})
  • components文件夾下Menu.vue文件的代碼
<!-- components/Menu.vue -->

<template>
  <nav>
    <ul>
      <li v-show="isShow">{{ $route.name }} </li>
      <li><router-link to="/">Home</router-link></li>
      <li><router-link to="/movies">Movies</router-link></li>
    </ul>
  </nav>
</template>

<script>
import { defineComponent } from 'vue'
import { useStore } from 'pinia'

export default defineComponent({
  name: 'Menu',

  setup() {
    const store = useStore('movie')

    return {
      isShow: store.getIsShow(),
    }
  },
})
</script>
  • components文件夾下MovieList.vue的代碼
<!-- components/MovieList.vue -->

<template>
  <ul>
    <li v-for="movie in movies" :key="movie.id">
      <router-link :to="`/movies/${movie.id}`">{{ movie.title }}</router-link>
    </li>
  </ul>
</template>

<script>
import { defineComponent } from 'vue'
import { useStore } from 'pinia'

export default defineComponent({
  name: 'MovieList',

  setup() {
    const store = useStore('movie')

    store.fetchMovies()

    return {
      movies: store.getMovies(),
    }
  },
})
</script>
  • views文件夾下MovieDetails.vue 的代碼
<!-- views/MovieDetails.vue -->

<template>
  <div v-if="movie">
    <h2>{{ movie.title }}</h2>
    <p>{{ movie.description }} </p>
  </div>
  <div v-else>
    <h2>Movie Not Found</h2>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'pinia'

export default defineComponent({
  name: 'MovieDetails',

  setup() {
    const route = useRoute()
    const store = useStore('movie')
    const movieId = route.params.id
    const movie = store.getMovies().find((movie) => movie.id === movieId)

    return {
      movie,
    }
  },
})
</script>

上面代碼展示了如何使用 Pinia 中的 store、getter 和 action 共享和管理狀態(tài)。其中,movieStore 定義了一個(gè)包含 isShow 和 movies 兩個(gè)狀態(tài)的 store,以及一個(gè)用于修改 isShow 和獲取電影列表的 action。在 Menu.vue 組件中,我們使用 useStore 鉤子從 store 中獲取 isShow 狀態(tài),并根據(jù)其值控制底部菜單欄 button 的顯示和隱藏。在 MovieList.vue 組件中,我們使用 useStore 鉤子從 store 中獲取 movies 狀態(tài),并使用 fetchMovies() action 來從網(wǎng)絡(luò)獲取電影列表。在 MovieDetails.vue 組件中,我們使用 useRoute 鉤子獲取當(dāng)前頁面的路由參數(shù) id ,使用 useStore 鉤子從 store 中獲取 movies 狀態(tài),并根據(jù) movieId 以及 getMovies() getter 得到當(dāng)前電影的詳細(xì)信息。

注意,在 setup() 鉤子中,我們使用 useStore 鉤子從 store 中獲取狀態(tài)和執(zhí)行操作。由于 useStore 鉤子返回的是一個(gè)響應(yīng)式的代理,因此我們無需手動(dòng)響應(yīng)式地更新狀態(tài)。而且,我們還可以將組件與 store 解耦,讓它們更易于測(cè)試和重用。

在組合式API中,實(shí)現(xiàn)代碼略有不同,這里只以MovieList.vue頁面舉例,其它頁面寫法類似,不在展示, MovieList.vue頁面代碼如下:

<!-- components/MovieList.vue -->

<template>
  <ul>
    <li v-for="movie in movies" :key="movie.id">
      <router-link :to="`/movies/${movie.id}`">{{ movie.title }}</router-link>
    </li>
  </ul>
</template>

<script setup>
import { onMounted, computed } from 'vue'
import { useStore } from 'pinia'

const store = useStore('movie')

onMounted(() => {
  store.fetchMovies()
})

const movies = computed(() => store.getMovies())
</script>

OK,關(guān)于Vue3中使用Pinia做全局狀態(tài)管理的使用就介紹到這里

總結(jié)

到此這篇關(guān)于Vue3中使用Pinia的方法文章就介紹到這了,更多相關(guān)Vue3使用Pinia內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • vue登錄路由權(quán)限管理的項(xiàng)目實(shí)踐

    vue登錄路由權(quán)限管理的項(xiàng)目實(shí)踐

    在開發(fā)Web應(yīng)用程序時(shí),常常需要進(jìn)行登錄驗(yàn)證和權(quán)限管理,本文主要介紹了vue登錄路由權(quán)限管理的項(xiàng)目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • Vue 自適應(yīng)高度表格的實(shí)現(xiàn)方法

    Vue 自適應(yīng)高度表格的實(shí)現(xiàn)方法

    這篇文章主要介紹了Vue 自適應(yīng)高度表格的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Vue從TodoList中學(xué)父子組件通信

    Vue從TodoList中學(xué)父子組件通信

    這篇文章主要介紹了Vue從TodoList中學(xué)父子組件通信,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2019-02-02
  • vue中進(jìn)入詳情頁記住滾動(dòng)位置的方法(keep-alive)

    vue中進(jìn)入詳情頁記住滾動(dòng)位置的方法(keep-alive)

    今天小編就為大家分享一篇vue中進(jìn)入詳情頁記住滾動(dòng)位置的方法(keep-alive),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-09-09
  • 10分鐘了解Vue3遞歸組件的用法

    10分鐘了解Vue3遞歸組件的用法

    遞歸?簡(jiǎn)單來講就是程序自己調(diào)用自身,vue中的遞歸組件就是,組件自身調(diào)用自身,下面這篇文章主要給大家介紹了關(guān)于Vue3遞歸組件的用法,需要的朋友可以參考下
    2022-03-03
  • Vue+better-scroll 實(shí)現(xiàn)通訊錄字母索引的示例代碼

    Vue+better-scroll 實(shí)現(xiàn)通訊錄字母索引的示例代碼

    通訊錄字母索引是常用的一種功能,本文主要介紹了Vue+better-scroll 實(shí)現(xiàn)通訊錄字母索引,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-06-06
  • VUE3中的函數(shù)的聲明和使用

    VUE3中的函數(shù)的聲明和使用

    這篇文章主要介紹了VUE3中的函數(shù)的聲明和使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-10-10
  • vue中使用animate.css實(shí)現(xiàn)炫酷動(dòng)畫效果

    vue中使用animate.css實(shí)現(xiàn)炫酷動(dòng)畫效果

    這篇文章主要介紹了vue中使用animate.css實(shí)現(xiàn)動(dòng)畫效果,我們使用它,只需要寫很少的代碼,就可以實(shí)現(xiàn)非常炫酷的動(dòng)畫效果,感興趣的朋友跟隨小編一起看看吧
    2022-04-04
  • vue中組件<router-view>使用方法詳解

    vue中組件<router-view>使用方法詳解

    這篇文章主要給大家介紹了關(guān)于vue中組件<router-view>使用方法的相關(guān)資料,Vue 路由中的 <router-view/> 是用來承載當(dāng)前級(jí)別下的子級(jí)路由的一個(gè)視圖標(biāo)簽,此標(biāo)簽的作用就是顯示當(dāng)前路由級(jí)別下一級(jí)的頁面,需要的朋友可以參考下
    2024-06-06
  • vue mixins合并策略以及應(yīng)用場(chǎng)景分析

    vue mixins合并策略以及應(yīng)用場(chǎng)景分析

    這篇文章主要介紹了vue mixins合并策略以及應(yīng)用場(chǎng)景,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-08-08

最新評(píng)論