更简单的状态管理器 pinia
pinia-新状态管理器简介官网地址:https://pinia.web3doc.top/introduction.html优势可以对Vue2和Vue3做到很好的支持,也就是老项目也可以使
pinia-新状态管理器
简介
官网地址:
https://pinia.web3doc.top/introduction.html
优势
- 可以对Vue2和Vue3做到很好的支持,也就是老项目也可以使用Pinia。
- 抛弃了Mutations的操作,只有state、getters和actions.极大的简化了状态管理库的使用,让代码编写更加容易直观。
- 不需要嵌套模块,符合Vue3的Composition api ,让代码更加扁平化。
- 完整的TypeScript支持。Vue3版本的一大优势就是对TypeScript的支持,所以Pinia也做到了完整的支持。如果你对Vuex很熟悉的化,一定知道Vuex对TS的语法支持不是完整的(经常被吐槽)。
- 代码更加简洁,可以实现很好的代码自动分割。Vue2的时代,写代码需要来回翻滚屏幕屏幕找变量,非常的麻烦,Vue3的Composition api完美了解决这个问题。 可以实现代码自动分割,pinia也同样继承了这个优点。
用法
安装插件
npm install pinia
# or with yarn
yarn add pinia
# 安装特定版本的pinia
npm install pinia@2.0.11
示例用法采用vue3+vite环境进行演示
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import './style.css'
import { createPinia } from 'pinia';
const app =createApp(App)
// 创建pinia 实例
const pinia = createPinia()
// 挂载到 Vue 根实例上
app.use(pinia)
app.mount('#app')
store/index
import { defineStore} from 'pinia'
// import { userStore } from "./user";
export const mainStore = defineStore('main',{
state:()=>{
return {
txt:'测试文字:Hello World---',
count:10,
phone:12345678901,
}
},
getters:{
phoneHidden(state){
return state.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
},
phoneHiddenb():String{
// console.log(this)
return this.phone.toString().replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
}
},
actions:{
changeState(){
// console.log(this)
this.count++;
this.txt = this.txt+'123=='
},
getList(){
// console.log(userStore().info)
}
}
})
在组件中使用
<script setup lang="ts">
import { ref } from 'vue'
import { mainStore } from "../store/index";
const store = mainStore();
console.log(store.txt)
defineProps<{ msg: string }>()
const count = ref(0)
// 第一种方法修改数据
const handleClick = () => {
store.count++;
console.log(store.$state)
};
// 第二种方式 $path 同时修改多个数据
const handlePathClick = () => {
store.$patch({
count:store.count+2,
txt:store.txt+'abc-'
});
};
// 第三种方式 $path 传递函数 处理复杂逻辑
const PathClick = () => {
store.$patch((state)=>{
state.count++;
});
};
</script>
<template>
<div>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<div>{{store.txt}} - {{store.count}}</div>
<p style="cursor: pointer;" @click="handleClick">点击修改数量</p>
<p style="cursor: pointer;" @click="handlePathClick">$path修改多组数据</p>
<p style="cursor: pointer;" @click="PathClick">$path传递函数</p>actions
<p style="cursor: pointer;" @click="store.changeState()">actions函数</p>
<p style="cursor: pointer;" @click="store.getList()">actions函数</p>
</div>
</div>
</template>
<style scoped>
</style>
相关文章
发表评论
评论列表
- 这篇文章还没有收到评论,赶紧来抢沙发吧~