pinia安装和使用

安装 :

npm install pinia

state: 状态。
actions: 修改状态(包括同步和异步,Pinia 中没有 mutations)。
getters: 计算属性。

main.ts :

import { createApp } from 'vue'
import './style.css'
import ElementPlus from 'element-plus'
import locale from "element-plus/lib/locale/lang/zh-cn";//element-plus中文版
import App from './App.vue'
import router from "./router/index" 
import 'element-plus/theme-chalk/index.css' 	
import { createPinia } from 'pinia'
// 创建pinia实例
const pinia = createPinia()

const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000,locale }) //element-plus中文版,加入locale
app.use(router).use(pinia).mount('#app')

store/main.ts :

import { defineStore } from 'pinia'
export const useMainStore =  defineStore('main', {
  state: () => {
    return {
      count: 1,
      users:[{id:1}]
    }
  },
  getters: {
    doubleCount: (state) => state.count * 2,
    doublePlusOne(): number {
      return this.count * 2 + 1
    },
  },
  actions: {
    addCount() {
      this.count++
    }
  }
})

index.vue

<template>
  <div>
    {{ mainStore.count }}~{{ count }}<br/>
	{{ mainStore.doubleCount }}~{{ mainStore.doublePlusOne }}<br/>
    <button @click="getStore">+事件</button>
    <button @click="mainStore.addCount">调用actions的addCount方法</button>
  </div>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia'; 
import { useMainStore } from '@/store/main'; 
const mainStore = useMainStore()  
// 体验通过解构获取 pinia 的 state,解构出来的值不是响应式的
// 将 pinia 实例对象通过 storeToRefs 包裹起来的时候,里面的值就是响应式的了
const { count } = storeToRefs(mainStore)
// 按钮点击事件
const getStore = () => {
  mainStore.count++
}
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值