菜单
本页目录

Pinia

Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态。 Pinia 三个核心概念:

State:表示 Pinia Store 内部保存的数据(data)

Getter:可以认为是 Store 里面数据的计算属性(computed)

Actions:是暴露修改数据的几种方式。

虽然外部也可以直接读写Pinia Store 中保存的data,但是我们建议使用Actions暴露的方法操作数据更加安全。 安装Pinia

npm install pinia

使用pinia

//main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import {createPinia} from 'pinia'

const pinia = createPinia();

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

定义存储库

选项式写法

stores/money.js编写内容;

//money.js
import {defineStore} from 'pinia'

//定义一个 money存储单元,money时存储库的唯一标识
export const useMoneyStore = defineStore('money', {
    state: () => ({money: 100}),
    getters: {
        rmb: (state) => state.money,
        usd: (state) => state.money * 0.14,
        eur: (state) => state.money * 0.13,
    },
    actions: {
        win(arg) {
            this.money+=arg;
        },
        pay(arg){
            this.money -= arg;
        }
    },
});

其他组件使用

<!-- Wallet.vue -->
<script setup>
import  {useMoneyStore} from '../stores/money.js'
let moneyStore = useMoneyStore();

</script>

<template>
<div>
  <h2>¥:{{moneyStore.rmb}}</h2>
  <h2>$:{{moneyStore.usd}}</h2>
  <h2>€:{{moneyStore.eur}}</h2>
</div>
</template>

<style scoped>
div {
  background-color: #f9f9f9;
}
</style>


<!--game.vue  -->
<script setup>
import  {useMoneyStore} from '../stores/money.js'

let moneyStore = useMoneyStore();
function guaguale(){
  moneyStore.win(100);
}

function bangbang(){
  moneyStore.pay(5)
}
</script>

<template>
  <button @click="guaguale">刮刮乐</button>
  <button @click="bangbang">买棒棒糖</button>
</template>

<style scoped>

</style>

组合式写法

// money.js
export const useMoneyStore = defineStore('money', () => {
    const salary = ref(1000); // ref() 就是 state 属性
    const dollar = computed(() => salary.value * 0.14); //  computed() 就是 getters
    const eur = computed(() => salary.value * 0.13); // computed() 就是 getters

    //function() 就是 actions
    const pay = () => {
        salary.value -= 100;
    }

    const win = () => {
        salary.value += 1000;
    }

    //重要:返回可用对象
    return {salary,dollar,eur,pay,win}
})