vue3+ pinia 的初实用

固定不变的 : stores/index.js

import { createPinia } from "pinia"

const pinia = createPinia()

export default pinia

 

main.js


import { createApp } from 'vue'
import App from './App.vue'
import pinia from './stores'

createApp(App).use(pinia).mount('#app')

 

复制代码
定义 : stores/counter.js


import { defineStore } from "pinia";

// 定义关于counter的store
// 参数1 : 这个store的id 
// 参数2 : 对象 => 存数据
// 会返回一个函数 : 命名为 use+id
const useCounter  =  defineStore("counter",{
    state:()=>({
        count:99
    }),
    getters:{

    },
    action:{

    }
})

export default useCounter 
复制代码

 

复制代码
使用 : 

<template>
  <div class="id">
    <!-- 原本版本 -->
    count : {{ counterStore.count }}

    <!-- 简化版本-->
    count : {{ count }}

    <button @click="btn">+1</button>
  </div>
</template>

<script setup>
import useCounter from './stores/counter';
import { toRefs } from 'vue';
const counterStore = useCounter()

// 简化版本
const { count } = toRefs(counterStore)

const btn = ()=>{
  counterStore.count++
}

</script>

<style>

</style>
复制代码

 

posted @   杨建鑫  阅读(68)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示