当前位置:网站首页>[boutique] detailed explanation of Pinia
[boutique] detailed explanation of Pinia
2022-06-29 19:37:00 【Liangyunliang】
brief introduction
pinia Is the latest generation of lightweight state management plug-ins .
advantage :
- Simple and convenient , Storage and components become very similar , You can easily write elegant storage .
= Type safety , Infer by type , It can provide the function of automatic completion .
= vue devtools Support , It is convenient for debugging .
= Pinia Support extended , Can be easily stored locally , Things, etc . - Modular design , By building multiple enclosures , Can let the program automatically split them .
- Very lightweight , Only about 1kb Size .
- Server side rendering support .
- complete ts Support for ;
- Remove mutations, Only state,getters,actions;
- actions Support synchronous and asynchronous ;
- Code flattening without module nesting , Only store The concept of ,store Can be used freely between , every last store They're all independent
- There is no need to manually add store,store Once created, it is automatically added ;
- Support Vue3 and Vue2
Installation configuration
- Installation command :
npm install pinia -S
- main.ts To configure
import {createPinia} from 'pinia'
const store= createPinia()
app.use(store)
adopt state modify
- stay state/index.ts In the file :
import {
defineStore} from "pinia"
export const useUserStore = defineStore('user', {
state: () => {
return {
name:'',
age: 0
}
}
})
- Demo.vue
<template>
{
{ user .name }}------{
{ user .age }}
<br>
<el-button type="primary" @click="user.age++"> Directly modifying </el-button>
<el-button type="primary" @click="fun1"> Bulk changes </el-button>
<el-button type="primary" @click="fun2"> Bulk changes : Functional writing </el-button>
<el-button type="primary" @click="fun3"> Modify all values </el-button>
</template>
<script setup lang="ts"> import {
useUserStore} from "@/store"; const user = useUserStore() const fun1 = ()=>{
//$patch Method can modify multiple values in batch user.$patch({
name:' Zhang San ', age:1234 }) } const fun2 = ()=>{
// Business logic can be written here ( Recommended ) user.$patch((state)=>{
if (state.name ==''){
state.age =6666 }else {
state.age =8888 } }) } const fun3 = ()=>{
//$state: Set as a new object to replace store The whole state of . Deficiency limit : All values must be modified user.$state = {
name:'zhangsan', age :3333 } } </script>
- result

adopt actions modify
stay actions You can do synchronous or asynchronous operations in .
actions Methods in can call each other .
- store/index.ts
import {
defineStore} from "pinia"
export const useCountStore = defineStore('count', {
state: () => {
return {
count: 0
}
},
actions: {
increment() {
this.count++
},
setCount(p: number) {
this.count = p
},
// Asynchronous operations
decrement() {
setTimeout(() => {
this.count--
}, 1000)
},
async sth(){
const tmp = await 1234
this.count = tmp
this.setCount(7878) // call
}
}
})
- Demo.vue
<template>
{
{ counter.count }}
<br>
<el-button type="primary" @click="fun1"> With the help of actions modify </el-button>
<el-button type="primary" @click="fun2"> With the help of actions modify </el-button>
<el-button type="primary" @click="counter.decrement"> Asynchronous operations </el-button>
<el-button type="primary" @click="counter.sth"> Asynchronous operations </el-button>
</template>
<script setup lang="ts"> import {
useCountStore} from "@/store"; const counter = useCountStore() // With the help of actions modify const fun1 = ()=>{
counter.increment() } // With the help of actions modify const fun2 = ()=>{
counter.setCount(789) } </script>
- result

getters
No matter how many times you call ,getters The function in will only be executed once , And will cache
- store/index.ts
import {
defineStore} from "pinia"
export const useCountStore = defineStore('count', {
state: () => {
return {
count: 10
}
},
getters: {
// Ordinary functional form , have access to this
getCount(): number {
return this.count
},
// Arrow function form , Out of commission this
newCount: (state): number => {
return state.count + 5
},
getDoubleCount(state): number {
return state.count * 2 + this.getCount
}
}
})
- Demo.vue
<template>
{
{counter.count}} <br>
{
{ counter.getCount }} <br>
{
{ counter.getCount }} <br>
{
{ counter.newCount }} <br>
{
{ counter.getDoubleCount }} <br>
</template>
<script setup lang="ts"> import {
useCountStore} from "@/store"; const counter = useCountStore() </script>
- result

Deconstruction object
Deconstruction is mainly aimed at Store Medium state and getters.
Example 1
- store/index.js
import {
defineStore} from "pinia"
export const useCountStore = defineStore('count', {
state: () => {
return {
count: 10
}
},
getters: {
// Ordinary functional form , have access to this
getCount(): number {
console.info("getCount")
return this.count
}
},
actions: {
increment() {
console.info("increment")
this.count++
}
},
})
- Demo.vue
<template>
Response type :{
{counter.count}} <br>
After the attribute is deconstructed, the response expression is lost :{
{ count }} <br>
getters The method loses its response after deconstruction :{
{getCount}}
<br>
<el-button type="primary" @click="fun"> After the attribute is deconstructed, the response expression is lost </el-button>
<el-button type="primary" @click="increment">actions Method does not lose its response after deconstruction </el-button>
</template>
<script setup lang="ts"> import {
useCountStore} from "@/store"; const counter = useCountStore() // deconstruction const {
count, getCount, increment} = counter const fun = () => {
counter.count++ // After the attribute is deconstructed, the response expression is lost console.info(count) } </script>
- effect

Example 2
- store/index.js
import {
defineStore} from "pinia"
export const useCountStore = defineStore('count', {
state: () => {
return {
count: 10
}
},
getters: {
// Ordinary functional form , have access to this
getCount(): number {
console.info("getCount")
return this.count
}
},
actions: {
increment() {
console.info("increment")
this.count++
}
},
})
- Demo.vue
<template>
Response type :{
{counter.count}} <br>
After the attribute is deconstructed, the response expression is lost :{
{ count }} <br>
getters The method loses its response after deconstruction :{
{getCount}}
<br>
<el-button type="primary" @click="fun"> After the attribute is deconstructed, the response expression is lost </el-button>
</template>
<script setup lang="ts"> import {
useCountStore} from "@/store"; import {
storeToRefs} from "pinia"; const counter = useCountStore() // deconstruction const {
count, getCount} = storeToRefs(counter) const fun = () => {
counter.count++ // After the attribute is deconstructed, the response expression is lost console.info(count) } </script>
- effect

pinia Commonly used API
- store/index.ts
import {
defineStore} from "pinia"
export const useCountStore = defineStore('count', {
state: () => {
return {
count: 10
}
},
actions: {
increment() {
console.info("increment")
this.count++
}
},
})
- Demo.vue
<template>
{
{counter.count}}
<br>
<el-button type="primary" @click="counter.count++"> Self increasing </el-button>
<el-button type="primary" @click="counter.increment()">actions: Self increasing </el-button>
<el-button type="primary" @click="counter.$reset()"> Reset the status data to the final status </el-button>
</template>
<script setup lang="ts"> import {
useCountStore} from "@/store"; const counter = useCountStore() //state Trigger when a change occurs counter.$subscribe((args,state)=>{
console.info(args,state) }) // monitor actions The method in counter.$onAction(args=>{
console.info(args) args.after(()=>{
console.info("after") }) }) </script>
- result
边栏推荐
- JVM (4) bytecode technology + runtime optimization
- 云服务器的安全设置常识
- DAO 中存在的不足和优化方案
- KDD 2022 | 協同過濾中考慮錶征對齊和均勻性
- 2022年理财利率都降了,那该如何选择理财产品?
- Lingyun going to sea | Wenhua online &huawei cloud: creating a new solution for smart teaching in Africa
- Game Maker 基金会呈献:归属之谷
- 虎符限币种提现 用户曲线出金即亏损
- Tiger painter mengxiangshun's digital collection is on sale in limited quantities and comes with Maotai in the year of the tiger
- Win11系统小组件打不开?Win11系统小组件无法打开解决方法
猜你喜欢

【精品】pinia详解

Shell bash script note: there must be no other irrelevant characters after the escape character \ at the end of a single line (multi line command)

mysql远程连接

Canonical的工程师们正努力解决Firefox Snap的性能问题

【观察】软通动力刘天文:拥抱变化“顺势而为”,做中国数字经济“使能者”...

k线图经典图解(收藏版)

罗清启:高端家电已成红海?卡萨帝率先破局

Win11 system component cannot be opened? Win11 system widget cannot be opened solution

正则表达式系列之手机号码正则

软件工程专业大二,之前的学习情况不太好该怎么规划后续发展路线
随机推荐
软件工程专业大二,之前的学习情况不太好该怎么规划后续发展路线
创作者基金会 6 月份亮点
畫虎國手孟祥順數字藏品限量發售,隨贈虎年茅臺
Mba-day19 if P then q contradictory relation P and not Q
雲服務器的安全設置常識
jfinal中如何使用过滤器监控Druid监听SQL执行?
3-3 host discovery - layer 4 discovery
一小时构建示例场景 声网发布灵隼物联网云平台
MBA-day26 数的概念与性质
PHP Laravel 使用 aws 负载均衡器的 ip 错误问题
正则表达式系列之手机号码正则
Arm comprehensive computing solution redefines visual experience and powerfully enables mobile games
3-2主机发现-三层发现
誰在抖音文玩裏趁亂打劫?
1404萬!四川省人社廳關系型數據庫及中間件軟件系統昇級采購招標!
[software testing] 01 -- software life cycle and software development model
以其他组件为代价的性能提升不是好提升
3-3主機發現-四層發現
【软件测试】01 -- 软件生命周期、软件开发模型
[proteus simulation] matrix keyboard interrupt scanning