当前位置:网站首页>Basic use of Pinia
Basic use of Pinia
2022-07-24 03:00:00 【Mangosteen is home】
- No, mutation、 No nested modules , relative vuex Yes ts There is better support
Click the official website link
One 、 install
npm install pinia
Two 、 Initialize configuration
src\main.ts
import {
createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {
createPinia } from 'pinia'
// establish pinia example
const pinia = createPinia()
const app = createApp(App)
// Mount to vue The root instance
app.use(pinia)
app.mount('#app')
3、 ... and 、 Basic use
3.1 establish store And use state Value
- src\store\index.ts
import {
defineStore } from "pinia";
// 1. Define and export containers
// Parameters 1: Container of ID, Must be unique , future pinia Will mount all containers to the root container
// Parameters 2: Option object
// Return value : A function , Call to get the container instance
export const useMainStore = defineStore('main', {
/** * Similar components data, Used to store the global state * 1. It has to be a function : This is to avoid data state pollution caused by cross requests when rendering on the server * 2. Must be an arrow function */
state: () => {
return {
count: 19
}
},
/** * Similar to component computed, Used to encapsulate calculated properties , With cache function */
getters: {
},
/** * Similar to component methods, Encapsulate business logic , modify state */
actions: {
}
})
- src\components\HelloWorld.vue
- Be careful not to deconstruct directly to get value , Otherwise, it is not responsive , Use official storeToRefs()
<script setup lang="ts">
import {
storeToRefs } from "pinia";
import {
useMainStore } from "../store/index";
const mainStore = useMainStore();
const {
count } = storeToRefs(mainStore);
console.log(mainStore.count);
const handleChangState = () => {
mainStore.count++;
};
</script>
<template>
{
{
mainStore.count }}=============={
{
count }}
<button @click="handleChangState"> Button </button>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>

3.2 Status update and actions
- In the case of multiple data modifications , Use $patch Good performance in batch modification
src\store\index.ts
import {
defineStore } from "pinia";
// 1. Define and export containers
// Parameters 1: Container of ID, Must be unique , future pinia Will mount all containers to the root container
// Parameters 2: Option object
// Return value : A function , Call to get the container instance
export const useMainStore = defineStore('main', {
/** * Similar components data, Used to store the global state * 1. It has to be a function : This is to avoid data state pollution caused by cross requests when rendering on the server * 2. Must be an arrow function */
state: () => {
return {
count: 19
}
},
/** * Similar to component computed, Used to encapsulate calculated properties , With cache function */
getters: {
},
/** * Similar to component methods, Encapsulate business logic , modify state */
actions: {
handleState(num: number) {
this.count += num
}
}
})
src\components\HelloWorld.vue
<script setup lang="ts">
import {
storeToRefs } from "pinia";
import {
useMainStore } from "../store/index";
const mainStore = useMainStore();
const {
count } = storeToRefs(mainStore);
const handleChangState = () => {
// Method 1 :
// mainStore.count++;
// Method 2 :
// mainStore.$patch({
// count: mainStore.count + 1,
// });
// Method 3 :
// mainStore.$patch((state) => {
// state.count++;
// });
// Method four :
mainStore.handleState(10);
};
</script>
<template>
{
{
mainStore.count }}=============={
{
count }}
<button @click="handleChangState"> Button </button>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
3.3getters
src\store\index.ts
import {
defineStore } from "pinia";
// 1. Define and export containers
// Parameters 1: Container of ID, Must be unique , future pinia Will mount all containers to the root container
// Parameters 2: Option object
// Return value : A function , Call to get the container instance
export const useMainStore = defineStore('main', {
/** * Similar components data, Used to store the global state * 1. It has to be a function : This is to avoid data state pollution caused by cross requests when rendering on the server * 2. Must be an arrow function */
state: () => {
return {
count: 19
}
},
/** * Similar to component computed, Used to encapsulate calculated properties , With cache function */
getters: {
count10(state) {
console.log(' See if it is cached ')
return state.count + 10
}
},
/** * Similar to component methods, Encapsulate business logic , modify state */
actions: {
}
})
<script setup lang="ts">
import {
storeToRefs } from "pinia";
import {
useMainStore } from "../store/index";
const mainStore = useMainStore();
</script>
<template>
{
{
mainStore.count10 }}
{
{
mainStore.count10 }}
{
{
mainStore.count10 }}
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>

边栏推荐
- Nodejs builds cloud native microservice applications based on dapr, a quick start guide from 0 to 1
- JVM初始
- Summary of problems encountered in the development process in July
- 日常杂谈(一)
- 322. Change
- The next stop of data visualization platform | gifts from domestic open source data visualization datart "super iron powder"
- LeetCode-栈和队列刷题
- Wonderful! The description of meituan Octo distributed service management system is too clear
- La chaîne entrante a des données lors de la transmission des paramètres JS; Aucune donnée n'a été transmise au numéro; 2 [0] Oui! Les données de type numéro peuvent être indexées
- 理解加载class到JVM的时机
猜你喜欢

508. The subtree element with the most occurrences and the pure C implementation of hash table method

The function of SIP account - tell you what is SIP line

【HDLBits 刷题】Verilog Language(2)Vectors 部分
[email protected] Principle of use"/>(6) Decorator extension [email protected] Principle of use

Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire

Interpretation of steam education with the deepening of educational reform
![JS when transferring parameters, the incoming string has data; No data when number is passed in; 2[0] is right! Number type data can be subscripted](/img/4e/3d0c25d9579b6d5c00473048dbbd83.png)
JS when transferring parameters, the incoming string has data; No data when number is passed in; 2[0] is right! Number type data can be subscripted

SkyWalking分布式系统应用程序性能监控工具-上

Attack and defense world web practice area (weak_auth, simple_php, xff_referer)

Babylon.js cool canvas background animation JS special effects
随机推荐
理解加载class到JVM的时机
Correlation
Summary of problems encountered in the development process in July
Liveqing live broadcast on demand streaming media OBS streaming live broadcast how to obtain interface verification token video verification streamtoken and configure token validity
Job hunting and recruitment system of SSM part-time job hunting
summernote富文本编辑器
Data Lake (XV): spark and iceberg integrate write operations
JVM initial
Ugui source code analysis - imaterialmodifier
Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire
og seo
Do securities companies really have principal guaranteed financial products?
Fasterrcnn sample code test 1: make anchor_ generator = None
Detailed vector
JS when transferring parameters, the incoming string has data; No data when number is passed in; 2[0] is right! Number type data can be subscripted
动态规划-01背包问题
How to get gait energy map Gei
Lcd1602——斌哥51
[brother hero July training] day 23: dictionary tree
The function of SIP account - tell you what is SIP line