欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > Vue3 pinia的安装和使用

Vue3 pinia的安装和使用

2025/6/22 8:21:31 来源:https://blog.csdn.net/HarryHY/article/details/148800281  浏览:    关键词:Vue3 pinia的安装和使用

安装

npm i pinia
pnpm i pinia

main.ts中引入

import { createPinia } from 'pinia'//引入createPinia用于创建pinia
app.use(createPinia())//使用pinia

组合式写法——Setup Store 更推荐

setup store更加灵活

ref() 就是 state 属性
computed() 就是 getters
function() 就是 actions

counter.ts —— pinia文件

import { ref, computed } from 'vue'
import { defineStore } from 'pinia' // 导入ref、computed和defineStore三个函数// 导出一个名为useCounterStore的常量,该常量是一个defineStore函数的返回值
export const useCounterStore = defineStore('counter', () => {// 定义一个名为count的ref变量,初始值为0const count = ref(0)// 定义一个名为doubleCount的computed变量,其值为count.value * 2const doubleCount = computed(() =>  `点击双倍${count.value * 2}`)// 定义一个名为increment的函数,每次调用时将count.value加1const add = () => {if(count.value < 10) count.value++}// 返回count、doubleCount和increment三个变量return { count, doubleCount, add }
})

获取store 使用

//页面<div @click="showNum">{{ doubleCount }}</div>
//js
import {storeToRefs} from 'pinia' //引入store ref化 解构响应式
import {useCounterStore} from '@/stores/counter.ts' //引入编写的pinia store文件
const counterStore = useCounterStore();
let {doubleCount,count}= storeToRefs(counterStore);//只有getter和state能使用storeToRefs
let {add} = counterStore;//action是函数 不需要用storeToRefs解构 也不能用
const showNum = ()=>{add()
}

注意,要让 pinia 正确识别 state,你必须在 setup store 中返回 state 的所有属性。这意味着,你不能在 store 中使用私有属性。不完整返回会影响 SSR ,开发工具和其他插件的正常运行。

选项式写法——Option Store

import { defineStore } from "pinia";// 导出一个名为 useUserStore 的 Pinia store,用于管理用户状态
export const useUserStore = defineStore("user", {// 定义 store 的状态state: () => ({ //定义一个store,用于管理用户状态// 初始化用户状态为 nulluser: 'zhangsan' as string | null,}),// 定义改变状态的方法actions: {// 设置用户状态setUser(user: any) {this.user = user;},// 清除用户状态clearUser() {this.user = null;},},// 定义基于状态的计算属性getters: {// 获取用户状态,当前为空,需要实现具体逻辑getUser: (state) => {return state.user;}}
})

获取

  <div @click="setUser('王五')">{{ user }}</div>
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/stores/user.ts'
let userStore = useUserStore()
let { user } = storeToRefs(userStore)
let {setUser} = userStore

VScode插件

Pinia Snippets

pinia官网
https://pinia.vuejs.org/zh/introduction.html

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词