天天看點

vite2 + Vue3中 使用 pinia

pinia中使用要比Vuex簡單。Vuex中有state、mutations、getters、actions、modules五種, 而 pinia中隻有state、getters、actions。寫法上有些不同。還是相對Vuex簡單的

安裝

yarn add pinia
# or with npm
npm install pinia      

main.js

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

const pinia = createPinia()

createApp(App)
.use(pinia)
.mount('#app')      
import { defineStore } from 'pinia'

/**
 *  1. 定義并導出容器
 *   參數1: 容器的 ID , 必須唯一, 将來 Pinia 會把所有的容器挂載到跟容器
 *   參數2: 選項對象
 *   傳回值: 一個函數, 調用得到容器執行個體
 */

export const useIndexStore = defineStore('index', {
  /**
   *  類似于元件的data, 用來存儲全局狀态
   *  1. 必須是函數,這樣是為了在服務端渲染的時候避免交叉請求導緻的資料狀态渲染
   *  2. 必須是箭頭函數, 這是為了更好的 TS 類型推導
   */
  state: () => {
    return {
      count: 100,
      quantity: 10
    }
  },

  /**
   *  類似于元件的computed, 用來封裝計算屬性, 有緩存的功能
   */
  getters: {
    // 接受一個可選參數 state 即 目前ID為index的Store執行個體  也可以用this 拿到 上面的state的狀态值
    countTotal(state) {
      return state.count * state.quantity
    }
  },

  /**
   * 類似于元件的 methods 封裝業務邏輯, 修改state
   * 通過 this  拿到上面 state的狀态值
   */
  actions: {
    countChange(val) {
      console.log(val,'actions中的參數--->>>>')
      this.count++
      this.quantity++

      // or
      // this.$patch({})
      // this.$patch(state => {})
    }
  }
})      

元件中使用 

<template>
  count: {{indexStore.count}}
  quantity: {{indexStore.quantity}}
  countTotal: {{indexStore.countTotal}}
  <hr>
  count: {{count}}
  quantity: {{quantity}}
  countTotal: {{countTotal}}
  <hr>
  <el-button type="primary" @click="indexStoreChange">修改state資料</el-button>
</template>

<script setup>
import { useIndexStore } from '@/store'
import { storeToRefs } from 'pinia'


//  state、getters、actions 裡面屬性或者方法  都是通過 indexStore “點” 出來使用的
const indexStore = useIndexStore()

//  如果想将狀态資料結構出來直接使用  必須引入storeToRefs(否則不是響應式) 來自于 pinia(類似于 reactive響應式,結構使用toRefs)
const { count, quantity, countTotal } = storeToRefs(indexStore)


//  修改state中的資料
const indexStoreChange = () => {
  // // 方式一: 最簡單的方式就是這樣
  // indexStore.count++
  // indexStore.quantity++

  // // 方式二:如果修改多個資料,建議使用 $patch 批量更新
  // indexStore.$patch({
  //   count: indexStore.count + 1,
  //   quantity: indexStore.quantity + 1
  // })

  // // 方式三(推薦都使用這個就好): 更好的批量更新的方式: $patch 一個函數  這種性能更好
  // indexStore.$patch(state => {
  //   state.count++
  //   state.quantity++
  // })

  // 方式四: 邏輯比較多的時候  可以狀态到 actions 中  調用 actions中的方法處理
  indexStore.countChange()
}


</script>

<style scoped>
  
</style>