VueHow to use Pinia state management tool in the project? The following article will talk about the use of Pinia state management tools in Vue projects. I hope it will be helpful to you!
Pinia official website says: Pinia is a repository for Vue that allows you to share state across components/pages. Vuex can also be used as a state management tool, so what is the difference between the two?
defineStore( )
The first parameter of the method: the name of the container, the name must be unique and cannot be repeateddefineStore( )
The second parameter of the method: configuration object, place state, getters, actionsstate
Attributes: Used to store the global stategetters
Attributes: Used to monitor or calculate state changes, with caching functionactions
Attribute: Modify state global state data, which can be asynchronous or synchronousPinia
Can be used in vue2.x or vue3.x
yarn add pinia -S
main.js
Introductionimport {createApp} from "vue" import App from "./app.vue" import store from "./store/index.js" const app = createApp(App); const store = createPinia(); app.use(store).mount("#app")
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存储配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
When using actions, you cannot use arrow functions because the arrow function binding is external this. This in actions points to the current store
import {createPinia} from "pinia" const store = createPinia(); export default store
A.vue
component, introduces the store module and storeToRefs
method storeToRefs
: Deconstruct the data in store
and make it responsive data <template> <div> <div> {{tname}}</div> <div> {{tid}}</div> <div> tnum: {{tnum}}</div> <div> {{tchangeNum}}</div> <div><button @click="tchangeName">修改</button></div> <div> <button @click="treset">重置</button></div> <div @click="actionsBtn">actionsBtn</div> </div> </template>
<script setup> import { storeToRefs } from 'pinia' import { useStore } from '../store/user' import { useTest } from '../store/test.js' const testStore = useTest(); let { tname, tchangeNum, tnum } = storeToRefs(testStore) </script>
Compared with using $path
to modify data directly, the official has made it clear$patch The
method is optimized and will speed up the modification, which is of great benefit to the performance of the program. So if you update status data with multiple pieces of data at the same time, it is recommended to use the $patch
method to update.
Although it can be modified directly, due to the code structure, global state management should not modify the state directly at each component. It should be modified in a unified method in actions
(piain does not have mutations) .
//直接修改数据 tchangeName(){ tname.value = "测试数据"; tnum.value++; } //当然也可以使用`$path`批量修改 tchangeName(){ testStore.$path(state=>{ state.tname = "测试数据"; state.value = 7; }) }
Directly call the method in actions
, and you can pass parameters
const actionsBtn = (){ testStore.addNum(5) }
$reset method in
#store, which can directly reset the data in
store
const treset = (){ testStore.$reset() }
yarn add pinia-plugin-persist
file under the
store folder. Introduce
pinia-plugin-presistplugin
import {createPinia} from "pinia" import piniaPluginPresist from "pinia-plugin-presist" const store = createPinia(); store.use(piniaPluginPresist) export default store
attribute to configure
import {definePinia} from "pinia" export default testStore = definePinia('testId',{ state:()=>{ tname:"test", tnum:0, }, getters:{ changeTnum(){ console.log("getters") this.tnum++; } }, actions:{ addNum(val){ this.tnum += val } }, //持久化存储配置 presist:{ enable:true,// strategies:[ { key:"testId", storage:localStorage, paths:['tnum'] } ] } })
, enable persistent storage, the default is to use
sessionStorage to store
-, proceed More configuration
-, when the key is not set, the key of storage is the first attribute of
definePinia. If the key value is set, the attribute name of storage is customized
, set the cache mode to local storage
, if not set, the data used in
state will be processed Persistence storage, when setting, only the set attributes are persistently stored
user.js file. Then the configuration content is the same as other modules, set according to your own needs, and then introduced on the corresponding page.
test.jsGet
user.js中
The name
attribute value of state is introduced in
test.js
user.js
import { defineStore } from 'pinia' import { userStore } from "./user.js" export const useTest = defineStore("testId", { state: () => { return { tid: "111", tname: "pinia", tnum: 0 } }, getters: { tchangeNum() { console.log('getters') return this.tnum + 100 } }, actions: { tupNum(val) { console.log('actions') this.tnum += val; }, getUserData() { console.log(useStore().name); return useStore().name; }, }, persist: { //走的session enabled: true, strategies: [ { key: "my_testId", storage: localStorage, paths: ['tnum'] } ] } })
user.js中
import { defineStore } from 'pinia' export const useStore = defineStore('storeId', { state: () => { return { num: 0, name: '张三' } } })
A.vue (学习视频分享:编程基础视频) The above is the detailed content of A brief analysis of how to use Pinia state management tool in Vue projects. For more information, please follow other related articles on the PHP Chinese website! component, call the
getUserData method in
test.js to get
uesr.js#name
value in ##
const actionBtn = () => {
testStore.getUserData()
};