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

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

相关推荐
燃先生._.4 小时前
Day-03 Vue(生命周期、生命周期钩子八个函数、工程化开发和脚手架、组件化开发、根组件、局部注册和全局注册的步骤)
前端·javascript·vue.js
南宫生5 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
sanguine__5 小时前
Web APIs学习 (操作DOM BOM)
学习
冷眼看人间恩怨5 小时前
【Qt笔记】QDockWidget控件详解
c++·笔记·qt·qdockwidget
数据的世界017 小时前
.NET开发人员学习书籍推荐
学习·.net
2401_857600957 小时前
SSM 与 Vue 共筑电脑测评系统:精准洞察电脑世界
前端·javascript·vue.js
2401_857600957 小时前
数字时代的医疗挂号变革:SSM+Vue 系统设计与实现之道
前端·javascript·vue.js
GDAL7 小时前
vue入门教程:组件透传 Attributes
前端·javascript·vue.js
轻口味7 小时前
Vue.js 核心概念:模板、指令、数据绑定
vue.js
四口鲸鱼爱吃盐7 小时前
CVPR2024 | 通过集成渐近正态分布学习实现强可迁移对抗攻击
学习