pinia的安装和使用

Administrator 10 阅读 博客

1.什么是 pinia?

pinia是一个类似于vuex的状态管理工具

2.inia和vuex的区别

  • pinia 最初是为了探索 Vuex 的下一次迭代会是什么样子

  • 与 Vuex 相比,Pinia 提供了一个更简单的 API,具有更少的仪式,提供了 Composition-API 风格的 API;

  • 最重要的是,在与 TypeScript 一起使用时具有可靠的类型推断支持;

3.安装和使用

1.安装

yarn add pinia
# 或者使用 npm
npm install pinia

2.使用

  • 在根目录新建store文件,store中新建index.js文件

    // stores/counter.js
    import { defineStore } from 'pinia';
    
    export const useCounterStore = defineStore('counter', {
        state: () => {
            return { count: 0 };
        },
        getters:{
            //获取参数
            getCount:state=>state.count
        },
        // 也可以这样定义
        // state: () => ({ count: 0 })
        actions: {
            increment() {
                this.count++;
            },
        },
    });
    
  • 在main.js中导入

    import {createPinia} from 'pinia'
    const store = createPinia()
    let app = createApp(App) 
    
    app.use(store)
  • 在具体模块中使用

    <template>
      <div class="about">
        <h1>{{counter.count}}</h1>
        <button @click="count++" type="button">count+</button>
        <button @click="add" type="button">count+1</button>
        <!-- getters获取数据 -->
        {{counter.getCount}}
      </div>
    </template>
    <script setup>
    import { useCounterStore } from '@/store';
    
        const counter = useCounterStore();
        const add=()=>{
            counter.increment()
        }
    </script>
  • pipia的解构

import {storeToRefs} from 'pinia'
const counter = useCounterStore();
const {count} = storeToRefs(counter)