pinia大菠萝快速上手

234 阅读1分钟

第一步:安装依赖
yarn add pinia or npm i pinia
第二步:在main.js中创建createpinia

import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
createApp(App).use(createPinia()).mount('#app')

第四步:定义store

import { defineStore } from "pinia";

const useUserStore = defineStore('userStore', {
    state: ()=> {
        return {
            userName: 'heihei',
        }
    },

    actions: ()=>{

    },
    getters: ()=>{

    }
})
export default useUserStore;

storeId为id名,可自定义,只要不与其他重复即可,其配置对象与vuex使用方法一致,删减了mutations和 modules两个配置对象 第五步:在组件中调用定义好的store即可

<script setup>
import useUserStore from '../store/uerStore';

    const userStore = useUserStore();

</script>
<template>
    Home
</template>

注意:

  1. pinia中store可以创建多个;
  2. 定义defineStore并没有直接创建store,而是定义了一个创建store的函数。