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

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

相关推荐
sanguine__3 分钟前
java学习-集合
学习
lxlyhwl3 分钟前
【STK学习】part2-星座-目标可见性与覆盖性分析
学习
nbsaas-boot4 分钟前
如何利用ChatGPT加速开发与学习:以BPMN编辑器为例
学习·chatgpt·编辑器
dr李四维6 分钟前
iOS构建版本以及Hbuilder打iOS的ipa包全流程
前端·笔记·ios·产品运营·产品经理·xcode
星星会笑滴40 分钟前
vue+node+Express+xlsx+emements-plus实现导入excel,并且将数据保存到数据库
vue.js·excel·express
CV学术叫叫兽43 分钟前
一站式学习:害虫识别与分类图像分割
学习·分类·数据挖掘
我们的五年1 小时前
【Linux课程学习】:进程程序替换,execl,execv,execlp,execvp,execve,execle,execvpe函数
linux·c++·学习
Backstroke fish1 小时前
Token刷新机制
前端·javascript·vue.js·typescript·vue
临枫5411 小时前
Nuxt3封装网络请求 useFetch & $fetch
前端·javascript·vue.js·typescript
RAY_CHEN.1 小时前
vue3 pinia 中actions修改状态不生效
vue.js·typescript·npm