The use of VUE3-Pinia "three"

Pinia's official website is Introduction | Pinia .

Its function is similar to vuex, but pinia is better than vuex. It is mainly used for state management and global variable management. It can also store the value of page A, and then directly access it in page B. Regardless of the relationship between parent and child components, it can pass values ​​arbitrarily, which is very flexible.

Let's do a simple case below, store a value in a page, refresh the current interface, the stored value will not be cleared

1. Use HBuilder X to create a program

2. Install pinia

npm install pinia

Enter the above command, after the installation is complete, you can see the version in the package file, and it is successful.

 

In order to persist the cache and avoid the problem of data clearing due to refreshing the interface, you need to install pinia-plugin-persistedstate. Many people have not installed it, so the data will not be stored after refreshing.

npm i pinia-plugin-persistedstate

As above, enter the command to install

3. In the main.js file, quote separately, the code is as follows

import { createApp } from 'vue'
import App from './App.vue'

import { createPinia } from 'pinia'
import persistedstate from "pinia-plugin-persistedstate"

const pinia = createPinia();
pinia.use(persistedstate);

const app = createApp(App)
app.use(pinia)
app.mount('#app')

4. Create a folder store, and then create a PiniaStore.js

the code 

import {
	ref
} from 'vue'
import {
	defineStore
} from 'pinia'

export default defineStore('testStore', () => {

	const info = ref({
		counter: 0, //记录访客次数
		enabled: 0,
		personID: '0',
		username: '0',
		password: '0',
	})

	return {
		info
	}

}, {
	persist: {
		storage: localStorage,
		paths: ['info']
	}
})

5. Use, delete the useless code in HelloWorld.vue, and only put the useful code

Import first, then assign

<template>
	123
</template>

<script setup>
	import useTestStore from "../store/PiniaStore.js"

	const counterStore = useTestStore();
	counterStore.info.username = 'admin'; //个人信息
	counterStore.info.password = '123456';
	counterStore.info.counter++
</script>

<style scoped>

</style>

6. At this point, we open Google Chrome, and then press F12. If vue devtools is installed, select VUE.

Plug-in installation learning front-end records_Hometown 2130's Blog-CSDN Blog 

You can see the variables inside

 

If we refresh the interface, the counter value will automatically increase, and the other values ​​will not change, which is actually a success.

Guess you like

Origin blog.csdn.net/u012563853/article/details/128194945