Vue3+ts中Pinia的基本使用

Pinia

  • Pinia 是 Vue 的存储库,它允许您跨组件/页面共享状态
  • 去除 mutations,只有 state,getters,actions;
  • actions 支持同步和异步;

1、安装

// yarn安装方式
yarn add pinia
// npm安装方式
npm install pinia

2、创建pinia文件

store文件里index.ts

import { defineStore } from 'pinia'
// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useStore = defineStore('main', {
    state:()=> {
        return {
            name: 'zs',
            age: 18
        }
    },
    getters: {

    },
    actions: {

    }
})

3、main.js导入并引用


import { createApp } from 'vue'
import App from './App.vue'
// 引入pinia
import {createPinia} from 'pinia'
 
const store = createPinia()

let app = createApp(App)
 
app.use(store)
 
app.mount('#app')

4、页面使用


<template>
  <div>
    {{user.name}}----{{user.age}}
  </div>
</template>

<script setup lang="ts">
import { useStore } from './store'

const user = useStore()


</script>

<style scoped>

</style>

你可能感兴趣的:(vue.js,javascript,前端)