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

pinia的基本使用

html 复制代码
<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

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

html 复制代码
<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

html 复制代码
import { defineStore } from 'pinia'

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

export default useUser

pinia的核心Getters

html 复制代码
<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

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

网络请求

html 复制代码
<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

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

stores/home

js 复制代码
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

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

相关推荐
黑叶白树2 分钟前
简单的签到程序 python笔记
笔记·python
@小博的博客5 分钟前
C++初阶学习第十弹——深入讲解vector的迭代器失效
数据结构·c++·学习
幸运超级加倍~40 分钟前
软件设计师-上午题-15 计算机网络(5分)
笔记·计算机网络
南宫生1 小时前
贪心算法习题其四【力扣】【算法学习day.21】
学习·算法·leetcode·链表·贪心算法
getaxiosluo1 小时前
react jsx基本语法,脚手架,父子传参,refs等详解
前端·vue.js·react.js·前端框架·hook·jsx
理想不理想v1 小时前
vue种ref跟reactive的区别?
前端·javascript·vue.js·webpack·前端框架·node.js·ecmascript
懒惰才能让科技进步1 小时前
从零学习大模型(十二)-----基于梯度的重要性剪枝(Gradient-based Pruning)
人工智能·深度学习·学习·算法·chatgpt·transformer·剪枝
love_and_hope2 小时前
Pytorch学习--神经网络--搭建小实战(手撕CIFAR 10 model structure)和 Sequential 的使用
人工智能·pytorch·python·深度学习·学习
Chef_Chen2 小时前
从0开始学习机器学习--Day14--如何优化神经网络的代价函数
神经网络·学习·机器学习
栈老师不回家2 小时前
Vue 计算属性和监听器
前端·javascript·vue.js