【VUE3】保姆级基础讲解(五)vuex续,pinia状态管理

上接:【VUE3】保姆级基础讲解(四): vue-router,vuex_独憩的博客-CSDN博客

目录

actions

基本使用

mapActions解构

Actions发送网络请求

modules

 基本使用

子模块getters

 命名空间

pinia状态管理

pinia与vuex的对比

创建pinia的store

pinia核心概念state

基础使用

 直接操作state

 重置state

 替换state为新的对象

pinia核心概念getters

pinia核心概念actions


actions

基本使用

  • action提交的是mutations,而不是直接变更状态
  • action可以包含任何异步操作
    mutations:{
        changename(state,newname){
            state.name = newname
        }
    },
    actions:{
        changenameAction(context){
            context.commit('changname')
        }
    }

 actions有一个非常重要的参数context

  • context是一个和store实例有相同方法和属性的对象
  • 可以使用context.commit来提交一个mutation,也可以通过context.statecontext.getters获取state和getters

 在组件中使用,使用dispatch调用actions中的函数

options api

<script>
  import { useStore, mapMutations } from 'vuex'
  export default {
    methods: {
      changename(){
        this.$store.dispatch('changenameAction')
      }
    }
  }
</script>

setup:

  const store = useStore()
  const changename=()=>{
    store.dispatch('changenameAction')
  }

mapActions解构

<script>
  import { useStore, mapActions } from 'vuex'
  export default {
    methods: {
      ...mapActions(['changenameAction'])
    }
  }
</script>

那么就可以直接在模板中使用 changenameAction函数

Actions发送网络请求

    const store = useStore()
    store.dispatch('fetchdataAction')
import {createStore} from  'vuex'
const store = createStore({
    state:()=>{
        return{
            banner:[],
            recommend:[]
        }
    },
    getters:{
    },
    mutations:{
        addbanner(state,data){
            state.banner = data
        },
        addrecommend(state,data){
            state.recommend = data
        }
    },
    actions:{
        fetchdataAction(context){
            fetch('http://123.207.32.32:8000/home/multidata').then((res)=>{
                res.json().then((data)=>{
                    console.log(data);
                    context.commit('addbanner',data.data.banner.list)
                    context.commit('addrecommend',data.data.recommend.list)

                })
            })
        }
    }
})
export default store

上面提供了一个完整方案:

  1. 在组件中调用actions中的fetchdataAction操作
  2. fetchdataAction函数中定义了一个异步操作,拿到数据后,提交mutations请求
  3. mutations中的函数再去修改state中的状态
  4. 组件再去使用state中的状态

 

modules

  • 由于使用单一状态树,应用的所有状态会集中到一个比较大的对象,当应用变得非常复杂时,store对象就有可能变得相当臃肿;
  • 为了解决以上问题,Vuex允许我们将store 分割成模块(module) ;
  • 每个模块拥有自己的state、mutation、action、getter、甚至是嵌套子模块;
     

 基本使用

子模块:

export default{
    state:()=>{
        return{
            banner:[],
            recommend:[]
        }
    },
    getters:{
    },
    mutations:{
        addbanner(state,data){
            state.banner = data
        },
        addrecommend(state,data){
            state.recommend = data
        }
    },
    actions:{
        fetchdataAction(context){
            fetch('http://123.207.32.32:8000/home/multidata').then((res)=>{
                res.json().then((data)=>{
                    console.log(data);
                    context.commit('addbanner',data.data.banner.list)
                    context.commit('addrecommend',data.data.recommend.list)

                })
            })
        }
    }
}

store对象,需要先引入子模块,再调用modules

import {createStore} from  'vuex'
import homemodules from './modules/home'
const store = createStore({
    modules:{
        home:homemodules
    }
})
export default store

那么在组件中使用时:

调用子模块的数据,在模板中需要$store.state.组件名称.数据(这里的命名方式后续说明)

$store.state.home.banner

但是在js代码中,就不需要区分哪个组件,直接调用函数名就ok 

    store.dispatch('fetchdataAction').then(res=>{
        console.log(111);
    })

子模块getters

子模块的getters可以有三个参数

    getters:{
        doublecount(state,getters,rootState){
            return state.count+rootState.counter
        }
    },

state为子模块的state,getters是子模块的getters,rootState是根store的state

在组件中调用时$store.getters.函数名称

    <h1>{{$store.getters.doublecount}}</h1>

只有在模板中调用state时,$store.state.组件名称.数据,才需要加组件名称

调用getters、mutations、actions都不需要组件名称,因为默认是将模块的这三个东西直接添加到根store中的

那么对模块中的这三个东西命名时,要格外小心,不能与跟store中的命名重复

 命名空间

上面我们说到,在命名时要避免重复,但是这样会造成代码编写难度

我们可以创建命名空间,只需要在模块开始加上    namespaced:true,

export default{
    namespaced:true,
    state:()=>{
        return{
        }
    },
    getters:{

    },
    mutations:{}

}

那么在组件中调用时,就必须注明模板名称

state的调用还是跟之前一样$store.state.组件名称.数据

getters、mutations、actions则需要:$store.getters['组件名称/方法名称']

    <h1>{{$store.getters['home/doublecount']}}</h1>

在js中调用也是一样

    store.dispatch('home/fetchdataAction').then(res=>{
        console.log(111);
    })

 

pinia状态管理

pinia与vuex的对比

什么是pinia?

  • Pinia开始于大概2019年,最初是作为一个实验为Vue重新设计状态管理,让它用起来像组合式APl(Composition API)。
  • 从那时到现在,最初的设计原则依然是相同的,并且目前同时兼容Vue2、Vue3,也并不要求你使用Composition APl;
  • Pinia本质上依然是一个状态管理的库,用于跨组件、页面进行状态共享(这点和Vuex、Redux一样);

和vuex相比,Pinia有很多的优势:

  • 比如mutations不再存在:

            √他们经常被认为是非常冗长;
            √他们最初带来了devtools集成,但这不再是问题;

  • 更友好的TypeScript支持,Vuex之前对Ts的支持很不友好;
  • 不再有modules的嵌套结构:

             √你可以灵活使用每一个store,它们是通过扁平化的方式来相互使用的;

  • 也不再有命名空间的概念,不需要记住它们的复杂关系;
     

 什么是Store?

  • 一个Store (如 Pinia)是一个实体,它会持有为绑定到你组件树的状态和业务逻辑,也就是保存了全局的状态
  • 它有点像始终存在,并且每个人都可以读取和写入的组件;
  • 你可以在你的应用程序中定义任意数量的store来管理你的状态;

Store有三个核心概念:

state、getters、actions;
等同于组件的data、computed、methods;
一旦store被实例化,你就可以直接在store上访问state、getters和actions中定义的任何属性;

 

创建pinia的store

  • 安装pinia
npm i pinia
  • 创建pinia实例并导出

 一般会在src文件夹下创建一个pinia文件夹,下面有一个index.js

import {createPinia} from 'pinia'
const pinia = createPinia()
export default pinia
  • 使用 defineStore定义Store

pinia文件夹下另外创建js文件放置store,这个文件下可以创建很多Store

defineStore('Store名字',{Store内容}),返回一个函数

import {defineStore} from 'pinia'

const useCounter = defineStore('counter',{  //返回一个函数
  
})
export default useCounter

defineStore('user',{
    
})

 

pinia核心概念state

基础使用

import {defineStore} from 'pinia'

const useCounter = defineStore('counter',{  //返回一个函数
    state:()=>{
        return{
            count:99
        }
    } 
})
export default useCounter

 在组件中需要先引入这个 useCounter函数,并运行这个函数,得到store对象

<script setup>
    import useCounter from'../piniastores/counter.js'
    const counterStore = useCounter()
</script>

 在模板中使用,不再需要区分state等

<template>
    <h1>{{counterStore.count}}</h1>
</template>

 也可以使用storeToRefs函数解构:

    import useCounter from'../piniastores/counter.js'
    import {storeToRefs} from 'pinia'
    const counterStore = useCounter()
    const{count}=storeToRefs(counterStore)

那么就可以直接使用count变量了

 直接操作state

与vuex不同,pinia可以直接操作state

<script setup>
    import useCounter from'../piniastores/counter.js'
    import {storeToRefs} from 'pinia'
    const counterStore = useCounter()
    const changestate = ()=>{
        counterStore.count++
    }
</script>

 重置state

    const resetState=()=>{
        counterStore.$reset()
    }

 替换state为新的对象

    const changeState = ()=>{
        counterStore.$state={
            count:999,
            age:18
        }
    }

这里需要注意一点,这个操作只会存在 替换和添加 

意思就是,例如我原来有A,B,C三个变量,现在使用$state={A=XXX,D=XXX},那么最终的结果会有A,B,C,D四个变量,会将没有改变的变量保存下来

pinia核心概念getters

import {defineStore} from 'pinia'
const useCounter = defineStore('counter',{  //返回一个函数
    state:()=>{
        return{
            count:99,
        }
    },
    getters:{
        doubleCount(state){
            return state.count*2
        }
    }     
})
export default useCounter

在组件中

    <h1>{{counterStore.doubleCount}}</h1>

也可以引用getters的函数

    getters:{
        doubleCount(state){
            return state.count*2
        },
        doubleCountone(){
            return this.doubleCount+1
        }
    }

其他一些用法跟vuex一直

pinia核心概念actions

普通的用法和getters一样,这里不赘述了

actions执行异步操作

import {defineStore} from 'pinia'

const useCounter = defineStore('counter',{  //返回一个函数
    state:()=>{
        return{
            banner:[],
            recommend:[]
        }
    },
    actions:{
        async fetchdataAction(){
            const res = await fetch('http://123.207.32.32:8000/home/multidata')
            const data =await res.json()
//可以直接操作数据
            this.banner = data.data.banner.list
            this.recommend = data.data.recommend.list
        }
    }
})
export default useCounter

在使用时

    const counterStore = useCounter()
    counterStore.fetchdataAction()

总结来说 pinia比vuex更好用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值