vue3中pinia如何使用

下载pinia

npm install pinia

在main.ts中引入

import { createPinia } from 'pinia'
app.use(createPinia())

引入pinia

位置src->stores->index.ts

import { defineStore } from 'pinia'

定义pinia

我们得知道 Store 是用 defineStore() 定义的,它的第一个参数要求是一个独一无二的名字

你可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。
export const useQueryStore = defineStore('query', () => {

  // state---data
  const queryValue = ref({})
  
  //getters ---computed
  const doubleCount = computed(() => queryValue .value.count * 2)

  //actions---methods
  function incrementQuery(row:object) {
    queryValue.value = row
  }

  return { queryValue,doubleCount, incrementQuery }
})

或者
与 Vue 的选项式 API 类似,我们也可以传入一个带有 state、actions 与 getters 属性的 Option 对象

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

使用pinia

方法一

<script lang="ts" setup>
import {useQueryStore} from "@/stores/counter"
const userStore = useQueryStore()
// 获取值
 queryValue.value = userStore.queryValue
// 修改值
 userStore.incrementQuery(row)
</script>

方法二

<script setup>
import { storeToRefs } from 'pinia'
const store = useCounterStore()
// `name` 和 `doubleCount` 是响应式的 ref
// 同时通过插件添加的属性也会被提取为 ref
// 并且会跳过所有的 action 或非响应式 (不是 ref 或 reactive) 的属性
const { name, doubleCount } = storeToRefs(store)
// 作为 action 的 increment 可以直接解构
const { increment } = store
</script>

参考
pinia官网https://pinia.vuejs.org/zh/core-concepts/state.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值