Pinia的使用(VUE3+VITE)

官方地址

https://pinia.vuejs.org/zh/

安装

​​​​​​​npm install pinia

挂载插件

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

createApp(App).use(createPinia()).mount('#app')

定义 Store(选项式或组合式)


选项式写法

import { defineStore } from 'pinia'

export const useCountStore = defineStore('count', {
  state: () => ({
    count: 10,
  }),
  getters: {
    // 普通函数可使用this拿到count
    // doubleCount(): number {
    //   return this.count * 2
    // },

    // 箭头函数使用state参数拿到count
    doubleCount: (state) => {
      return state.count * 2
    },
  },

  actions: {
    addV2(value: number) {
      this.count += value
    },
  },
})

组合式写法

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

export const useCountStore = defineStore('count', () => {
  const count = ref(10)
  const doubleCount = computed(() => {
    return count.value * 2
  })
  function addV2(value: number) {
    count.value += value
  }
  function $reset() {
    count.value = 10
  }
  return {
    count,
    doubleCount,

    addV2,
    $reset,
  }
})

访问 state和getter






访问actions






你可能感兴趣的:(vue.js,前端,javascript)