Vue的通用组件通信工具——Vuex和Pinia入门指南

Vue状态管理工具Vuex与Pinia入门


一、Vuex

工作流程

在这里插入图片描述

具体介绍

  • vc.$store.dispatch(‘方法’,参数):参数传入 actions 对应方法中

  • vc.$store.commit(‘方法’,参数):参数直接传入 mutations 对应方法中

  • store.actions:用于响应组件中的动作(业务逻辑层)

    const actions = {
        方法名(context,value){
            context.commit("方法名",value)
        }//context表示上下文,是处理过的store,有需要的方法,包括commit、dispatch、state等
    }
    
  • store.mutations:用于操作数据(数据访问层)

    const mutations = {
        方法名(state,value){
            state.属性 = 属性值2
        }//接收的state是处理过的state
    }
    
  • store.state:用于存储数据

    const state = {
        属性:属性值1
    }
    
  • store.getters:用于将state中的数据进行加工

    const getters = {
        加工后属性名(state){
            加工过程
            return 加工结果
        }
    }
    

示例

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const actions = {
    test(context,value){
        context.commit("test",value)
    }
}
const mutations = {
    test(state,value){
        state.test1 = "test22"
    }
}
const state = {
    test1:"test11"
}
const getters = {
    test1a(state){ 
        return state.test1 += "a" 
    }
}
export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters,
})

//main.js(全局注册,vm和vc都有$store)
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})

//使用state时,可以封装到 computed 中,并使用 vuex 提供的 mapState、mapGetters 方法自动书写代码,以mapState为例
<script>
    import {mapState} from 'vuex'
	export default {
        name:"xxx",
        data(){},
        computed:{
            ...mapState({
                别名1:'属性名1',
                别名2:'属性名2',
            }),//对象写法,这里没有简写形式
            /*等价于
            别名1(){return this.$store.state.属性名1},
        	别名2(){return this.$store.state.属性名2},*/
            ...mapState(['属性名3','属性名4']),//不重命名用数组写法
            /*等价于
            属性名3(){return this.$store.state.属性名3},
        	属性名4(){return this.$store.state.属性名4},*/
        },
        methods:{
            //commit相关也可以自动书写,使用 mapMutations ,注意模板中要传参
            ...mapMutations({
                方法名1:'mutations中的方法名1',
                方法名2:'mutations中的方法名2',
            }),//对象写法
            /*等价于
            方法名1(){this.$store.commit('mutations中的方法名1',参数)},
        	方法名2(){this.$store.commit('mutations中的方法名2',参数)},*/
            ...mapMutations(['mutations中的方法名3','mutations中的方法名4']),
            //数组写法,方法名要相同
            //dispatch相关自动书写,使用 mapActions ,注意模板中要传参,同上
        }
    }
</script>

模块化编码和命名空间

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import 外部vuex模块c from ...
Vue.use(Vuex)
const a = {
    //配合vue文件中...mapState('a',['属性名1','属性名2']),
    //配合vue文件中...mapMutations('a',['mutations中的方法名1','mutations中的方法名2']),
    namespaced:true,
    vuex模块
}
const b = {
    //配合vue文件中...mapState('b',['属性名3','属性名4']),
    //配合vue文件中...mapMutations('b',['mutations中的方法名3','mutations中的方法名4']),
    namespaced:true,
    vuex模块
}
export default new Vuex.Store({
	modules: {
		a,
        b,
        c,
	},
    //属性通过如下方式访问
    //$store.state.a.属性名
    //$store.getters['a/属性名']
    //方法通过如下方式触发
    //$store.dispatch('a/方法名',参数)
    //$store.commit('a/mutations中的方法名',参数)
    //相关模块开启命名空间,自动生成代码函数要添加命名空间参数
})

二、Pinia

更符合直觉的 Vue.js 状态(数据)管理库

定义 Store

import { defineStore } from 'pinia'

//  `defineStore()` 的返回值的命名是自由的
// 但最好含有 store 的名字,且以 `use` 开头,以 `Store` 结尾。
// (比如 `useUserStore`,`useCartStore`,`useProductStore`)
// 第一个参数是你的应用中 Store 的唯一 ID。
export const useTestStore = defineStore('test', {
  // 其他配置...
})

defineStore() 的第二个参数可接受两类值:Option 对象(选项式)或 Setup 函数(组合式) 。

Option Store

export const useCounterStore = defineStore('counter', {
  state: () => ({ count: 0, name: 'Eduardo' }),
  getters: {
    doubleCount: (state) => state.count * 2,
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

可以认为 state 是 store 的数据 (data),getters 是 store 的计算属性 (computed),而 actions 则是方法 (methods)。

Setup Store

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const name = ref('Eduardo')
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, name, doubleCount, increment }
})

在 Setup Store 中:

  • ref() 就是 state 属性
  • computed() 就是 getters
  • function() 就是 actions

Store的基本使用

<script setup>
    // 使用storeToRefs()需要从pinia中引入storeToRefs
    import { storeToRefs } from 'pinia'
    import { useCounterStore } from '@/stores/counter'
    const counterStore = useCounterStore()
    // 在组件内部的任何地方均可以访问 'counterStore' 的属性和方法,如counterStore.name,counterStore.increment()
    // 也可以解构,但`counterStore` 是一个用 `reactive` 包装的对象,对它进行解构会破坏其响应式,需要storeToRefs()
    const { name,doubleCount } = storeToRefs(counterStore)
    //方法不需要响应式,可以直接解构
    const { increment } = counterStore
</script>

State的进阶使用

pinia持久化插件

安装插件

 npm i pinia-plugin-persistedstate

将插件添加到 pinia 实例中

import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

使用

在声明store时,将新persist选项设置为 true(在组合式写法中作为第三个对象参数)


总结

  • Vuex采用集中式存储,通过单一状态树管理全局状态,强调严格的流程控制(如mutations同步修改状态)。
  • Pinia采用去中心化架构,允许多个独立store共存,提供更灵活的模块组织方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Demoncode_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值