Vuex与Pinia的使用与其持久化以及两者之间的差别

vuex在vue3的简单使用

index.js文件
		import { createStore } from 'vuex'
export default createStore({
    state: {
        num: 10,
        sum:20,
        strValue:'这是vuex中的数据'
    },
    getters: {
        total(state) {
            return state.num+state.sum
         }
    },
    mutations: {
        changeNum(state,value) {
            state.num = value
        },
    },
    actions: {
        changeSum(context,value) { 
            context.commit('changeNum',value)
        }
    },
    modules: {},
})

如何使用mutations中的方法以及何如使用actions中的方法请看index.vue组件

<template>
  <div>
    <h1>这是vuex测试文件</h1>
    <div>{{ num }}==>{{ total }}</div>
    <button @click="btn">修改vuex中的值</button>
  </div>
</template>

<script setup>
import { useStore } from "vuex";

let store = useStore();
console.log(store);
let num = computed(() => store.state.num);
let total = computed(() => store.getters.total);
const btn = () => {
  // 这里是使用mutations中的方法
  //   store.commit("changeNum", 300);
  //   这里是使用actions中的方法
  store.dispatch("changeSum", 666);
};
</script>

<style>
</style>

actions和mutitions的区别

actions和mutations都能够使用方法,那么他们的区别是什么,那我去查了很多贴子:无非就是说mutations中的方法是同步的,而actions中的方法是异步的,其实根据场景来使用吧,你想要程序按照顺序来执行,那么你就使用mutations,如果你这个数据不是很急着使用想要下面的先执行,那么你就可以使用actions
vuex中的state数据不允许直接赋值修改,所以vuex创建了mutations用于定义方法来修改state中的数据,但是只能同步修改。如果异步修改会造成调试工具跟实际数据不对应,所以vuex又提供了actions,用于异步触发mutations中的方法。
总结:mutations中的方法可以直接修改state数据,actions是异步执行mutations中的方法,所以它俩都可以改数据,区别是一个是同步一个是异步。

vuex持久化存储

yarn add vuex-persistedstate -s(使用这个插件)
持久化是存储到localStorage里面
如何去持久化呢:localStroage.removeItem(key)
只是说使用这么多的插件方便了一点点而已,自己写也可以写,只不过现在着实时间精力有限,先用着大佬写的。

import { createStore } from 'vuex'
import user from './modules/user'
import persistedState from 'vuex-persistedstate'
import * as Cookie from 'js-cookie'
export default createStore({
    state: {
        num: 10,
        sum:20,
        strValue:'这是vuex中的数据'
    },
    getters: {
        total(state) {
            return state.num+state.sum
         }
    },
    mutations: {
        changeNum(state,value) {
            state.num = value
        },
    },
    actions: {
        changeSum(context,value) { 
            context.commit('changeNum',value)
        }
    },
    modules: { user },
    // 配置持久化
    plugins: [persistedState({
        // 这个key是存储的名称
        key: 'persisted-vuex',
        // 这个是需要持久化的模块
        paths: ['user'],
    })]
})
user模块
		export default {
    //开启名称空间确实对自己友好一点
    namespaced:true,
    state: {
        userInfo:'userInfo'
    },
    getters: {

   },
    mutations: {
        updateUserInfo(state, value) { 
            state.userInfo=value
        }
    },
    actions: {
        UPDATE_USERINFO(context, value) { 
            context.commit('updateUserInfo',value)
        }
    }
}

index.vue文件

<template>
  <div>
    <h1>这是vuex测试文件</h1>
    <div>{{ num }}==>{{ total }}==>{{ userInfo }}</div>
    <button @click="btn">修改vuex中的值</button>
  </div>
</template>

<script setup>
import { useStore } from "vuex";

let store = useStore();
console.log(store);
let num = computed(() => store.state.num);
let total = computed(() => store.getters.total);
let userInfo = computed(() => store.state.user.userInfo);
const btn = () => {
  // 这里是使用mutations中的方法
  //   store.commit("changeNum", 300);
  //   这里是使用actions中的方法
  console.log(store.state.num);
  store.dispatch("changeSum", 666);
  console.log(store.state.num);
  //   修改模块化的modules中的User文件中userInfo的值
  //   commit修改
  // store.commit("user/updateUserInfo", "我是commit修改的值");
  // dispatch 名称一定要一一对应,我这里actions里面我现在采用的是全大写拼写,为了区分。。。。。
  store.dispatch("user/UPDATE_USERINFO", "我是dispatch修改的值");
};
</script>

<style>
</style>

pinia使用

并不是有了新技术就一定要用什么新技术吧,反正不断学习,自己判断,有时候最新的并不一点是最合适的。。。。。
pinia里面使用模块化是很方便的,不需要使用moudle,但是有一点需要注意的。自己看index文件,第二行注释。

index.js
		import { defineStore } from 'pinia'
//这里的storId不能够重复,不然直接没有数据,亲测。
export const useStore = defineStore('storId', {
    state: () => { 
        return {
            counter: 0,
            num: 1,
            age:20,
         }
    },
    getters: {
        changeNum() { 
            return this.num+120
        }
    },
    actions: {
        upCounter(val) { 
            this.counter+=val
        },
    }
})
	user.js
		import { defineStore
} from "pinia";
export const userStore = defineStore('userID', {
    state: () => { 
        return {username:'user.js文件'}
    }
    
})
使用(index.vue文件)
<template>
  <div>
    <h1>pinia测试</h1>
    <div>{{ age }}+++++{{ num }}+++++{{ changeNum }}++++++{{ counter }}</div>
    <div>{{ username }}</div>
    <button @click="btn">修改数据</button>
    <button @click="btnSection">批量修改</button>
    <button @click="manipulateActions">操作actions方法</button>
    <button @click="storeReset">重置store</button>
  </div>
</template>

<script setup>
// 引用useStore模块
import { useStore } from "../../piniaStore/index";
// 解构用的,为了能够让数据响应式
import { storeToRefs } from "pinia";
// 引用user模块
import { userStore } from "../../piniaStore/user";
const store = useStore();
// 通过storeToRefs可以建立响应式数据
let { age, num, changeNum, counter } = storeToRefs(store);
let { username } = storeToRefs(userStore());
let btn = () => {
  age.value = 88;
  num.value = 100;
};
let btnSection = () => {
  // 批量更改属性
  store.$patch((state) => {
    state.age++;
    state.num--;
  });
};
let manipulateActions = () => {
  // 使用方法actions内的方法
  store.upCounter(100);
};
let storeReset = () => {
  // 重置所有属性
  store.$reset();
};
</script>

<style>
</style>

Pinia数据持久化

普通的跟vuex差不多,localstroage,sessionstroage,Cookie里面
插件版本pinia-plugin-persistedstate(用这个插件)

together.js
import { createPinia } from "pinia";
import pinaPluginPersist from 'pinia-plugin-persistedstate'
const store = createPinia()
store.use(pinaPluginPersist)
export default store
index.js
				import { defineStore } from 'pinia'
export const useStore = defineStore('storId', {
    state: () => { 
        return {
            counter: 0,
            num: 1,
            age:20,
         }
    },
    getters: {
        changeNum() { 
            return this.num+120
        }
    },
    actions: {
        upCounter(val) { 
            this.counter+=val
        },
    },
    // 启动持久化
    persist: {
        // 是否开启
        enabled: true,
        // 持久化策略
        // 存储名称
        key: 'useStroage',
        // 存储位置
        stroage:window.localStorage
        
    }
})
			我这里只在index文件中开了
user.js
				import { defineStore
} from "pinia";
export const userStore = defineStore('userID', {
    state: () => { 
        return {username:'user.js文件'}
    }
    
})

pinia与vuex的区别

1.vuex不可以直接修改state中的属性的值,需要通过mutations或者actions中的方法来修改。pinia可以使用storeToRefs()来直接修改,也可以通过store.$patch(state=>{})来批量修改属性值也是没有问题的。
2.pinia中没有mutations,可以直接通过store对象来输出方法。
OS:这应该是程序员为了偷懒写的插件啊哈哈哈哈,我猜是的。真的挺方便的。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值