程序员鸡皮

文章 分类 评论
61 3 9

站点介绍

一名PHP全栈程序员的日常......

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

abzzp 2024-07-10 658 0条评论 前端 vue

首页 / 正文
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......

发布于2024-07-04

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

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

评论(0)

最新评论

  • abzzp

    十天看一部剧,还可以吧[[呲牙]]

  • ab

    @梦不见的梦 行,谢谢提醒,我优化一下

  • 梦不见的梦

    网站的速度有待提升,每次打开都要转半天还进不来呢

  • abzzp

    @React实战爱彼迎项目(二) - 程序员鸡皮 哪里有问题了,报错了吗?[[微笑]]

  • abzzp

    @Teacher Du 那是怕你们毕不了业,我大学那会儿给小礼品[[发呆]]

  • Teacher Du

    我们大学那会,献血还给学分~

  • @ab 我想去学网安,比如网警,但分也贼高😕

  • ab

    @夜 加油,你一样也可以成为程序员的,需要学习资料可以V我

  • 佬发布的好多技术文章似乎我只能评论这篇,真正的程序员!!哇塞 我也想去献血,过两年就成年了可以去献血了

日历

2025年01月

   1234
567891011
12131415161718
19202122232425
262728293031 

文章目录

推荐关键字: vue JavaScript React Golang 观后感 ES6 SEO 读后感

站点公告
本站是作为记录一名北漂程序员编程学习以及日常的博客,欢迎添加微信BmzhbjzhB咨询交流......
点击小铃铛关闭
配色方案