pinia

pinia初使用

npm install pinia

import { createPinia } from 'pinia'

app.use(createPinia())

可以直接创建一个pinia文件夹 列如 src/pinia/layout.ts

import { defineStore } from 'pinia'
// useLayout 也称为 id,是必要的,Pinia 使用它来将 store 连接到 devtools。 将返回的函数命名为 use... 是跨可组合项的约定,以使其符合你的使用习惯。
export const useLayout = defineStore('main', {
  // 是一个箭头函数
  state: () => {
    return {
      counter: 'holle',
    }
  },
  getters: {},
  actions: {
     setCounter() {
      this.counter = '你好'
    },
  },
})

页面使用

<template>
  <div>{{ counter }}</div>
  <button @click="checnges">改变</button>
</template>
<script setup lang="ts">
import { useLayout } from "@/pinia/layout";
import { storeToRefs } from "pinia";
// 如果想通过结构的方式拿到store数据就必须通过storeToRefs API去包裹,才能维持响应式数据
const { counter } = storeToRefs(useLayout());
const checnges = () => {
  // 这里支持直接修改
  useLayout().counter = "你好";
  // OR --同时修改多个时使用
  useLayout().$patch({
    counter: "你好",
  });
  // OR --同时修改多个时使用
  useLayout().$patch((store) => {
    store.counter = "你好";
  });
  // OR 通过 actions 内部写方法修改变量
  useLayout().setCounter();
};

</script>
<style lang="less" scoped>
</style>
posted @ 2022-12-24 16:52  小万子呀  阅读(81)  评论(0编辑  收藏  举报