Vue3 使用存储库Pinia(state)

一、store.js创建state

import { defineStore } from "pinia";
export const useStore = defineStore('main', {
    state() { // state表示这个store里的状态,也就是存放数据的地方
        return {
            name: '张三',
            age:'26' 
        }
    }
})

二、引用store.js

import {useStore} from "../store/store" // 引入store
const store = useStore()

三、html里展示

在这里插入图片描述

{{store.name}}:{{age}}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 的 Pinia 是一个基于 Composition API 的状态管理,用于在 Vue 3 应用程序中管理数据。下面是使用 Pinia 进行数据存储的一般步骤: 1. 安装 Pinia: ```bash npm install pinia ``` 2. 创建一个 Pinia 实例并导出它,以便在应用程序的入口文件中使用: ```javascript // src/store/index.js import { createPinia } from 'pinia'; export const pinia = createPinia(); ``` 3. 在应用程序入口文件(例如 `main.js`)中使用创建的 Pinia 实例: ```javascript import { createApp } from 'vue'; import App from './App.vue'; import { pinia } from './store'; const app = createApp(App); app.use(pinia); app.mount('#app'); ``` 4. 创建一个 store 文件,定义数据存储和相关操作: ```javascript // src/store/count.js import { defineStore } from 'pinia'; export const useCountStore = defineStore('count', { state: () => ({ count: 0, }), getters: { doubleCount() { return this.count * 2; }, }, actions: { increment() { this.count++; }, decrement() { this.count--; }, }, }); ``` 5. 在组件中使用数据存储: ```vue <template> <div> <p>Count: {{ count }}</p> <p>Double Count: {{ doubleCount }}</p> <button @click="increment">Increment</button> <button @click="decrement">Decrement</button> </div> </template> <script> import { useCountStore } from '../store/count'; export default { setup() { const countStore = useCountStore(); return { count: countStore.count, doubleCount: countStore.doubleCount, increment: countStore.increment, decrement: countStore.decrement, }; }, }; </script> ``` 通过以上步骤,你可以在 Vue 3 应用程序中使用 Pinia 进行数据存储。你可以定义状态、计算属性和操作,并在组件中使用它们。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值