vue3中pinia基本使用

一、安装以及引入

  • 安装:npm install pinia
  • main.js文件:
javascript 复制代码
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";

const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
    .mount("#app");

二、使用

1、基本使用

新建store/Count/index.js

javascript 复制代码
import { defineStore } from "pinia";
import { personStore } from "../Person/index";
export const useCounterStore = defineStore('counter', {
    // state: ()=>({name: 'alice',count: 0}),
    state: () => {
        return {
            count: 10,
            content: '~',
            users: [
                {name: 'alice', id: 1},
                {name: 'jack', id: 2},
                {name: 'rose', id: 3},
            ]
        }
    },
    getters: { 
        doubleCount: (state) => state.count * 2,
        // doublePlusOne:(state)=> state.doubleCount+1
        doublePlusOne() {
            return this.doubleCount + 1 // 可以访问其他getter
        },
        getUserById: (state) => { //  getter是计算属性 不可以向getter传递参数,可以从getter返回函数 给该函数可以传递参数
            return (userId) => state.users.find((user) => user.id === userId)
        },
        // 访问其他store
        getOtherStoreName:(state)=>{
            const perStore=personStore()
            return perStore.username+state.content
        }
    },
    actions: {
        increment() {
            this.count++
        },
        randomizeCounter(){
            this.count=Math.round(100*Math.random())
        }
    }
})

新建store/Person/index.js:

javascript 复制代码
import { defineStore } from "pinia";
export const personStore = defineStore('person', {
    state: () => {
        return {
            username: 'alice',
            age: 18,
     		sum: 0
        }
    },
    getters: {
        getName: (state) => `姓名:${state.username}`
    },
    actions: {
        changeName() {
            this.username = this.username + '~'
        }
    }
})

// 写法二
import {computed, ref} from 'vue'
export const personStore1 = defineStore('person', ()=>{
    const username=ref('alice')
    const age=ref(18)
    const sum=ref(0)
    const getName=computed(()=>`姓名: ${username.value}`)
    function changeName() {
        this.username=this.username+'~'
    }
    return {username,getName,changeName}
})

App.vue文件使用:

javascript 复制代码
<template>
  <div class="app">
   <ul>
    <li> count:{{ countStore.count }} {{ countStore.content }}</li>
    <li>double: {{ countStore.doubleCount }}</li>
    <li>double+1: {{ countStore.doublePlusOne }}</li>
   </ul>
   <div>{{ countStore.getUserById(3) }}</div>
  </div>
</template>

<script setup name="App">
import { useCounterStore } from "./store/Count";
import { personStore } from "../Person/index";
import { computed } from "vue";

const countStore = useCounterStore();
const userInfoStore = personStore()

// 作为action的increment可以直接解构
const {increment}=countStore
const doubleValue = computed(() => countStore.doubleCount);
console.log(countStore.count) // 访问仓库
// 通过subscribe方法监听state变化
countStore.$subscribe((mutation,state)=>{
	// 操作
})

// 修改仓库数据
// 第 1 种,直接修改
userInfoStore.sum = 99
// 第 2 种,利用 $patch 批量修改
userInfoStore.$patch({
  sum: 110,
  username: 'rose'
})
// 第 3 种,在 actions 中修改. 定义函数,this.xxx = xxx
</script>
2、插件使用

插件是一个函数,通过pinia.use()这个函数传递给pinia。插件接收一个可选参数context。该参数是一个包含app、pinia、store等实例的对象。

如果这个函数有返回值,返回值为一个对象,则该对象的所有属性都会被添加到每个store上。

每创建一个store实例,这个插件函数都会执行一遍。
main.js

javascript 复制代码
import { createApp } from "vue";
import { createPinia } from "pinia";
import App from "./App.vue";

const pinia = createPinia()
// 创建的每个 store 中都会添加一个名为 `secret` 的属性。
// 在安装此插件后,插件可以保存在不同的文件中
function SecretPiniaPlugin(context) {
  return { secret: 'the cake is a lie' }
}
// 将该插件交给 Pinia
pinia.use(SecretPiniaPlugin) // 将函数返回值secret作为静态属性添加到所有的store
pinia.use(content=>{
    console.log(content, content.store);
    
})

pinia.use(()=>({hello: 'world'}))
pinia.use(({store})=>{ // 最好使用返回对象的方法,以便于被开发者工具自动追踪
    store.address='newAddress'
})

const app = createApp(App)
app.use(pinia)
    .mount("#app");

在vue文件中使用:

javascript 复制代码
<template>
  <div class="app">  </div>
</template>

<script setup name="App">
import { useCounterStore } from "./store/Count";

const countStore = useCounterStore();

console.log(countStore.secret,'---'); // the cake is a lie---
</script>
相关推荐
苹果酱05676 小时前
iview 表单验证问题 Select 已经选择 还是弹验证提示
java·vue.js·spring boot·mysql·课程设计
Jiaberrr6 小时前
uniapp app 端获取陀螺仪数据的实现攻略
前端·javascript·vue.js·uni-app·陀螺仪
源码云商8 小时前
基于 SpringBoot + Vue 的校园管理系统设计与实现
vue.js·spring boot·后端
几度泥的菜花8 小时前
Vue 项目中二维码生成功能全解析
javascript·vue.js·ecmascript
LuckyLay10 小时前
AI教你学VUE——Deepseek版
前端·javascript·vue.js
我是哈哈hh10 小时前
【Vue】全局事件总线 & TodoList 事件总线
前端·javascript·vue.js·vue3·vue2
liuyang___11 小时前
vue3+ts的watch全解!
前端·javascript·vue.js
我是哈哈hh11 小时前
【Vue】组件自定义事件 & TodoList 自定义事件数据传输
前端·javascript·vue.js·vue3·vue2
牧杉-惊蛰11 小时前
VUE+ElementUI 使用el-input类型type=“number” 时,取消右边的上下箭头
前端·vue.js·elementui
工业互联网专业11 小时前
基于springboot+vue的社区药房系统
java·vue.js·spring boot·毕业设计·源码·课程设计·社区药房系统