vue中,pinia用法示例
Pinia 是一个用于 Vue.js 的状态管理库,与 Vuex 相似,但更简单和轻量级。它适用于 Vue 3,但也可在 Vue 2 中使用。
以下是 Pinia 的基本用法:
安装
首先,你需要安装 Pinia。
npm install pinia
或者
yarn add pinia
创建 Pinia 实例
在你的 Vue 应用中,你需要创建一个 Pinia 实例,并将其添加到应用实例中。
import { createPinia } from 'pinia'
import { createApp } from 'vue'
const app = createApp(YourApp)
app.use(createPinia())
app.mount('#app')
创建 store
接下来,你可以创建一个 store。每个 store 都有一些状态和可选的 actions。这是一个简单的示例:
import { defineStore } from 'pinia'
export const useMyStore = defineStore({
id: 'myStore',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
},
},
})
在组件中使用 store
然后,在你的 Vue 组件中,你可以使用
useMyStore
函数来访问和操作 store 中的状态。import { useMyStore } from '@/stores/myStore'
export default {
setup() {
const myStore = useMyStore()
return {
count: myStore.count,
increment: myStore.increment,
}
},
}
在模板中使用状态或者方法
你可以在 Vue 组件的模板里面直接访问这些状态变量或方法:
<template>
<div>
Count: {{ count }}
<button @click="increment">Increment</button>
</div>
</template>
以上是 Pinia 的基本用