美文网首页
vue3 pinia

vue3 pinia

作者: 洪锦一 | 来源:发表于2024-08-01 14:19 被阅读0次

Store是一个保存:状态业务逻辑 的实体,每个组件都可以读取写入它。
它有三个概念:stategetteraction,相当于组件中的: datacomputedmethods

1. 安装 npm install pinia

2. 在 main.js 中配置

const app = createApp(App)

// 第一步:引入pinia
import {createPinia} from 'pinia'

// 第二步:创建pinia
const pinia = createPinia()

// 第三步:安装pinia
app.use(pinia)

app.mount('#app')

3. 创建文件

  • 选项式
// store/count.js
import { defineStore } from 'pinia'

export const useCountStore = defineStore('count', {
    state() {
        return {
            sum: 6,
            name: 'Zs'
        }
    },
    actions: {
        increment(value) {
            this.sum = value;
        }
    },
    getters: {
        nameUpperCase() { return this.name.toUpperCase() }, // 大写
        nameLowerCase: state => state.name.toLowerCase(), // 小写(简写)
    }
})
  • 组合式
import { defineStore } from 'pinia'
import { computed, ref } from 'vue';

export const useCountStore = defineStore('count', () => {
    let sum = ref(16);
    let name = ref('Zs');

    const increment = (value) => {
        sum.value = value
    }

    const nameUpperCase = computed(() => name.value.toUpperCase())

    return { sum, name, increment, nameUpperCase }
})

4. 读取数据

<template>
  {{countStore.sum}} -  {{countStore.nameUpperCase}} -  {{countStore.nameLowerCase}}
  <el-button @click="handleClick">点我修改sum</el-button>
</template>
<script setup>
import { useCountStore } from "@/store/count";
const countStore = useCountStore()
</script>

5.修改数据

  • 第一种修改方式:直接修改
countStore.sum += 1
  • 第二种修改方式:批量修改
countStore.$patch({
  sum: 18,
  name: 'ls'
})
  • 第三种修改方式:借助action修改(action中可以编写一些业务逻辑)
countStore.increment(20);

6. storeToRefs

如果解构 store 中的数据,需要使用 storeToRefs 包裹,否则不是响应式
借助storeToRefsstore中的数据转为ref对象,方便在模板中使用。
pinia提供的storeToRefs只会将数据做转换,而VuetoRefs会转换store中数据。

<template>
  {{sum}}
  <el-button @click="handleClick">点我修改sum</el-button>
</template>
<script setup>
import { useCountStore } from "@/store/count";
import { storeToRefs } from "pinia";
const countStore = useCountStore()
const { sum } = storeToRefs(countStore) // 不使用storeToRefs 解构出来的sum不是响应式数据

const handleClick = () => {
  countStore.sum += 1
}
</script>

7. $subscribe

通过 store 的 $subscribe() 方法侦听 state 及其变化

countStore.$subscribe((mutate, state) => {
  console.log('countStore', mutate, state)
})

相关文章

网友评论

      本文标题:vue3 pinia

      本文链接:https://www.haomeiwen.com/subject/gdyohjtx.html