Pinia 的使用

pinia官网 :Pinia 中文文档

pinia的使用

1.安装pinia

如果你使用 npm

npm install pinia

或者你使用 Yarn

yarn add pinia

2.打开main.js文件注册pinia

import { createApp } from 'vue'
import { createPinia } from "pinia"
import App from './App.vue'
const app = createApp(App)
//注册pinia
app.use(createPinia())
app.mount('#app')

3.定义一个store

src/store/count.js

import { defineStore } from "pinia"
// useCountStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
//state函数返回的是定义属性名的初始值
export const useCountStore = defineStore("Count", {
    state: () => ({
        count: 0,
        name: "lining",
    }),

4.使用store

请注意,store 是一个用reactive 包裹的对象,这意味着不需要在getter 之后写.value,但是,就像setup 中的props 一样,我们不能对其进行解构

export default defineComponent({
  setup() {
    const store = useStore()
    // ❌ 这不起作用,因为它会破坏响应式
    // 这和从 props 解构是一样的
    const { name, doubleCount } = store

    name // "eduardo"
    doubleCount // 2

    return {
      // 一直会是 "eduardo"
      name,
      // 一直会是 2
      doubleCount,
      // 这将是响应式的
      doubleValue: computed(() => store.doubleCount),
      }
  },
})

为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()。 它将为任何响应式属性创建 refs。 当您仅使用 store 中的状态但不调用任何操作时,这很有用:

<template>
    <h1>我是Count组件</h1>
    <h2>Count:{{ count }}</h2>
    <h2>{{ name }}</h2>
    <button @click="addCount">+</button>&nbsp;
    <button @click="decCount">-</button>&nbsp;
    <button @click="resetInitial">重置初始状态</button>&nbsp;
</template>
    
<script setup lang='js'>
import { useCountStore } from '../store/count';
import { storeToRefs } from "pinia"
const countStore = useCountStore();
//结构赋值需要利用storeToRefs否则结构出来的值不会产生响应式效果
const { count, name } = storeToRefs(countStore)
const addCount = () => {
  //可以利用结构出来的值直接使用或修改值
      count.value++
    name.value = "Nike"
}
const decCount = () => {
    count.value--
}
const resetInitial = () => {
    //调用store身上的$reset(),可以重置state身上所有属性的初始值
    countStore.$reset()
}
</script>
    
<style></style>

若你需要重置state身上所有属性的初始值你可以调用$reset()

5.使用Actions

Actions 相当于组件中的 methods。 它们可以使用 defineStore() 中的 actions 属性定义,并且它们非常适合定义业务逻辑

import { defineStore } from "pinia"
import axios from "axios"
export const useCountStore = defineStore("Count", {
    state: () => ({
        count: 0,
        name: "lining",
        userInfo: []
    }),
    actions: {
        addition() {
            this.count++
        },
        subtraction() {
            this.count--
        },
      //actions 可以是异步的,您可以在其中await 任何 API 调用甚至其他操作! 
        async getUserData() {
            const result = await axios.get("https://jsonplaceholder.typicode.com/users")
            this.userInfo = result.data
        }
    }
})
<template>
    <h1>我是Count组件</h1>
    <h2>Count:{{ count }}</h2>
    <h2>{{ name }}</h2>
    <button @click="addCount">+</button>&nbsp;
    <button @click="decCount">-</button>&nbsp;
    <button @click="getAxiosData">获取axios的数据</button>
    <button @click="resetInitial">重置初始状态</button>&nbsp;
    <ul>
        <li v-for="item in userInfo " :key="item.id">{{ item.name }}</li>
    </ul>
</template>
    
<script setup lang='js'>
import { useCountStore } from '../store/count';
import { storeToRefs } from "pinia"
const countStore = useCountStore();
//结构赋值需要利用storeToRefs否则结构出来的值不会产生响应式效果
const { count, name, userInfo } = storeToRefs(countStore)
const addCount = () => {
    countStore.addition()
    name.value = "Nike"
}
const decCount = () => {
  //可以直接调用actions定义的函数
    countStore.subtraction()
    // count.value--
}
const getAxiosData = () => {
    countStore.getUserData()
}
const resetInitial = () => {
    //调用store身上的$reset(),可以重置state身上所有属性的初始值
    countStore.$reset()
}
</script>
    
<style></style>
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值