Vue3大菠萝pinia笔记
发布时间
阅读量:
阅读量
-
- pinia的基本特点
pinia同样是一个Vue
该状态管理工具在功能上与Vuex具有诸多相似之处。它是Vuex团队核心成员自行研发的,并在此基础上提出了若干改进措施。相较于Vuex框架而言,Pinia去除了对Mutations与Actions区分的划分。而直接在Actions属性中支持同步与异步操作(这也表明了Vuex开发计划中的相应调整)。相较于Vuex框架而言,Pinia在TypeScript语言支持方面表现更为出色,并且凭借友好的开发者工具界面进一步提升了用户体验。Pinia所占用的空间仅1KB,并大大简化了代码逻辑;基于其较为成熟的技术架构,在项目规模较小的情况下表现更为优异;而针对大型复杂项目需求,则更适合采用传统的Vuex解决方案。
-
- 基本配置和使用
//利用vue-cli创建一个pinia项目(这里选择创建vue3项目)
vue create pinia
//在项目中安装pinia
npm install pinia@next
项目中导入pinia
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
//需要注意的是从pinia中结构出来的createPinia是一个函数,挂载需要先调用执行
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
设置状态管理专用文档,在根目录中建立一个store.ts文件,并同时新增一个index.js.ts文件
import {defineStore} from 'pinia';
export const userTestStore = defineStore({//需要注意的是,defineStore返回的是一个回调方法
id:'test',//test是该状态管理的唯一标志也可以使用defineStore(id,{});的形式
state(){
return {
name:'hello pinia',
age:20
}
},
getters:{
testGetters(){
return this.name+'...';//直接利用this便能够获取到里面的内容不需要使用state中间对象
}
},
actions:()=>{
addAge:function(){
setInterval(()=>{
this.age++;
},1000)
}
}
})
-
- pinia传参与调用
下面给出调用store里面的带参方法例子:
//在状态管理工具中定义addAge函数
actions:{
addAge(gap){
this.age+=gap;
}
}
//组件中导入对应状态管理工具
import { userTestStore } from "./store";
const store = userTestStore();
const { addAge } = store;//解构出store实例里面的addAge方法
<div>output age:{{ store.age }}</div>
<button @click="addAge(10)">click for add age</button>
demo 修改store值得五种方式,推荐使用action
//store-name.ts
export const enum Names {
Test = 'Test'
}
// store.js
import { defineStore } from 'pinia'
// defineStore 调用后返回一个函数,调用该函数获得 Store 实体
import { defineStore } from "pinia";
import { Names } from "./store-name";
//定义的defineStore(),并且它需要一个唯一的名称,Names.Test名称抽离出去作为第一个参数传递
export const useTestStore = defineStore(Names.Test, {
state: () => ({ current: 1, name: '小满' }),
//computed:修饰一些值
getters: {
},
//methods:可以做同步异步,提交state
actions: {
setCurrent(type: boolean) {
//通过this指向属性
if (!type) return false
this.current++
}
}
})
// 在vue3中使用
<template>
<div>
pinia:{{ current }}---{{ Test.name }}
<button @click="setCur">set</button>
</div>
</template>
<script lang="ts" setup>
import { useTestStore } from './store';
const Test = useTestStore()
const current = computed(() => Test.current)
/** * state的五种方式修改值
1.直接修改值
Test.current=2
2.通过$patch修改,支持单个或多个属性修改
Test.$patch({current:33})
3.$patch工厂函数方式
Test.$patch((state) => {
state.current = 99;
state.name = '范迪塞尔'
})
4.$state 缺点是必须修改整个对象
Test.$state = { current: 88, name: '123' }
5.action
Test.setCurrent()
*/
const setCur = () => {
// Test.current = 2
// Test.$patch({ current: 33 })
Test.$patch((state) => {
state.current = 99;
state.name = '范迪塞尔'
})
Test.$state = { current: 88, name: '123' }
Test.setCurrent(true)
}
</script>
<style lang = "scss" scoped>
</style>
全部评论 (0)
还没有任何评论哟~
