Vue3中Pinia状态管理库学习笔记

47 篇文章 2 订阅
本文详细介绍了如何在Vue项目中使用Pinia库进行状态管理和getters功能的实践,包括基本使用、引入其他getter、函数式getter以及跨store数据获取。还涉及了如何处理网络请求并更新状态。
摘要由CSDN通过智能技术生成

pinia的基本使用


<template>
  <div>
    <h2>Home View</h2>  
    <h2>count:{{ counterStore.count }}</h2>
    <h2>count:{{ count }}</h2>
    <button @click="increment">count+1</button>
  </div>
</template> 
<script setup>
  import { toRefs } from 'vue'
  import useCounter from '@/stores/counter';
  const counterStore = useCounter()
  const { count } = toRefs(counterStore)
  function increment(){
    counterStore.count++
  }
</script>
<style scoped>
</style>

store/counter.js

// 定义关于counter的store
import { defineStore } from 'pinia'

import useUser from './user'
const useCounter = defineStore("counter",{
  state:()=>({
    count:99,
    friends:[
      {id:111,name:"why"},
      {id:112,name:"kobe"},
      {id:113,name:"james"},
    ]
  }),
  getters:{
    // 1.基本使用
    doubleCount(state){
      return state.count * 2
    },
    // 2.一个getter引入另一个getter
    doubleCountAddOne(){
      // this 是store实例
      return this.doubleCount+1
    },
    // 3.getters也支持返回一个函数
    getFriendById(state){
      return function(id){
        for(let i = 0;i<state.friends.length;i++){
          const friend = state.friends[i]
          if(friend.id === id){
            return friend
          }
        }
        // return state.friends.find()
      }
    },
    // 4.getters如果用到了别的store中的数据
    showMessage(state){
      // 1.获取user信息
      const userStore = useUser()

      // 2.获取自己的信息
      // 3.拼接信息
      return `name:${userStore.name}-count:${state.count}`
    }
  },
  actions:{
    increment(state){
      console.log(state)
      this.count++
    },
    incrementNum(num){
      this.count += num
    }
  }
})

export default useCounter

pinia的核心State

<template>
  <div>
    <h2>Home View</h2>  
    <h2>name:{{ name }}</h2>
    <h2>age:{{ age }}</h2>
    <h2>level:{{ level }}</h2>
    <button @click="changeState">修改state</button>
    <button @click="resetState">重置state</button>
  </div>
</template> 
<script setup> 
  import useUser from "@/stores/user";
  import { storeToRefs } from 'pinia';
  const userStore = useUser();
  // console.log(userStore)
  const { name,age,level } = storeToRefs(userStore)

  function changeState(){
    // 1. 一个个修改状态
    // userStore.name = "kobe"
    // userStore.age = 20
    // userStore.level = 200
    // 2.一次性修改多个状态
    // userStore.$patch({
    //   name:"james",
    //   age:35,
    // })
    // 3.替换state为新的对象
    const oldState = userStore.$state = {
      name:"curry",
      level:200
    }
    console.log(oldState === userStore.$state)
  }
  function resetState(){
    userStore.$reset()
  }
</script>
<style scoped>
</style>


store/user.js

import { defineStore } from 'pinia'

const useUser = defineStore("user",{
  state:()=>({
    name:"why",
    age:18,
    level:100
  })
});

export default useUser

pinia的核心Getters

<template>
  <div>
    <h2>Home View</h2>  
    <h2>doubleCount:{{ counterStore.doubleCount }}</h2>
    <h2>doubleCountAddOne:{{ counterStore.doubleCountAddOne }}</h2>
    <h2>friend-111:{{ counterStore.getFriendById(111) }}</h2>
    <h2>friend-112:{{ counterStore.getFriendById(112) }}</h2>
    <h2>showMessage:{{ counterStore.showMessage }}</h2>
    <button @click="changeState">修改state</button>
    <button @click="resetState">重置state</button>
  </div>
</template> 
<script setup> 
  import useCounter from '@/stores/counter';
  const counterStore = useCounter()
</script>
<style scoped>
</style>

store/counter.js

// 定义关于counter的store
import { defineStore } from 'pinia'

import useUser from './user'
const useCounter = defineStore("counter",{
  state:()=>({
    count:99,
    friends:[
      {id:111,name:"why"},
      {id:112,name:"kobe"},
      {id:113,name:"james"},
    ]
  }),
  getters:{
    // 1.基本使用
    doubleCount(state){
      return state.count * 2
    },
    // 2.一个getter引入另一个getter
    doubleCountAddOne(){
      // this 是store实例
      return this.doubleCount+1
    },
    // 3.getters也支持返回一个函数
    getFriendById(state){
      return function(id){
        for(let i = 0;i<state.friends.length;i++){
          const friend = state.friends[i]
          if(friend.id === id){
            return friend
          }
        }
        // return state.friends.find()
      }
    },
    // 4.getters如果用到了别的store中的数据
    showMessage(state){
      // 1.获取user信息
      const userStore = useUser()

      // 2.获取自己的信息
      // 3.拼接信息
      return `name:${userStore.name}-count:${state.count}`
    }
  },
  actions:{
    increment(state){
      console.log(state)
      this.count++
    },
    incrementNum(num){
      this.count += num
    }
  }
})

export default useCounter

网络请求

<template>
  <div>
    <h2>Home View</h2>  
    <h2>doubleCount:{{ counterStore.count }}</h2>
    <button @click="changeState">修改state</button>

    <!-- 展示数据 -->
    <h2>轮播的数据</h2>
    <ul>
      <template v-for="item in homeStore.banners" :key="item.id">
        <li>{{ item.title }}</li>
      </template>
    </ul>
  </div>
</template> 
<script setup> 
  import useCounter from '@/stores/counter';
  import useHome from '@/stores/home'
  const counterStore = useCounter()

  function changeState(){
    counterStore.increment();
    // counterStore.incrementNum(10);
  }

  const homeStore = useHome();
  homeStore.fetchHomeMultidata().then(res =>{
    
    console.log("fetchHomeMultidata的action已经完成了",res)
  });
</script>
<style scoped>
</style>

stores/counter

// 定义关于counter的store
import { defineStore } from 'pinia'

import useUser from './user'
const useCounter = defineStore("counter",{
  state:()=>({
    count:99,
    friends:[
      {id:111,name:"why"},
      {id:112,name:"kobe"},
      {id:113,name:"james"},
    ]
  }),
  getters:{
    // 1.基本使用
    doubleCount(state){
      return state.count * 2
    },
    // 2.一个getter引入另一个getter
    doubleCountAddOne(){
      // this 是store实例
      return this.doubleCount+1
    },
    // 3.getters也支持返回一个函数
    getFriendById(state){
      return function(id){
        for(let i = 0;i<state.friends.length;i++){
          const friend = state.friends[i]
          if(friend.id === id){
            return friend
          }
        }
        // return state.friends.find()
      }
    },
    // 4.getters如果用到了别的store中的数据
    showMessage(state){
      // 1.获取user信息
      const userStore = useUser()

      // 2.获取自己的信息
      // 3.拼接信息
      return `name:${userStore.name}-count:${state.count}`
    }
  },
  actions:{
    increment(state){
      console.log(state)
      this.count++
    },
    incrementNum(num){
      this.count += num
    }
  }
})

export default useCounter

stores/home

import { defineStore } from "pinia";

const useHome = defineStore("home",{
  state:()=>({
    banners:[],
    recommends:[]
  }),
  actions:{
    // async fetchHomeMultidata(){
    //   const res = await fetch("http://123.207.32.32:8000/home/multidata")
    //   const data = await res.json();
    //   this.banners = data.data.banner.list
    //   this.recommends = data.data.recommend.list

    //   return 'aaa';
    // }
    fetchHomeMultidata(){
      // eslint-disable-next-line no-async-promise-executor
      return new  Promise(async (resolve,reject)=>{
        const res = await fetch("http://123.207.32.32:8000/home/multidata")
        const data = await res.json();
        this.banners = data.data.banner.list
        this.recommends = data.data.recommend.list

        resolve("bbb")
      })
    }
  }
})
export default useHome

感谢大家观看,我们下次见

  • 21
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

2019ab

你的鼓励就是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值