在vue2中pinia的使用

该文介绍了如何在Vue应用中利用Pinia进行状态管理。首先在store的index.js文件中定义了一个store,包含counter状态和increment、randomizeCounter两个action。然后在main.js入口文件中注册了Pinia插件并创建了实例。文章提供了存储和调用state的方法,强调了import和useStore的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

步骤:

  1. 根据官网操作

  1. 通过百度网络csdn查询他人所写,查缺补漏

store中index.js

import { defineStore } from 'pinia'

export const useStore = defineStore('storeId', {
    // 推荐使用 完整类型推断的箭头函数
    state: () => ({
        counter: 90,
    }),
    actions: {
        increment(msg) {
           this.counter=msg
           console.log(msg);
        },
        randomizeCounter(msg) {
            this.counter = msg
        },
    },
})


入口函数main.js

步骤:

  1. 插件必须注册

import Vue from 'vue'
// import { createApp } from 'vue'
import App from './App.vue'
import { createPinia, PiniaVuePlugin } from 'pinia'

Vue.use(PiniaVuePlugin)
const pinia = createPinia()

new Vue({
  render: h => h(App),
  pinia,
}).$mount('#app')

存储与调用

//存储
import { useStore } from '@/store/index'
const store = useStore()
store.存储方法()

//调用
//与存储相同:导入+创建变量+调用方法

调用案例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值