likes
comments
collection
share

用Setup API来写Pinia.js

作者站长头像
站长
· 阅读数 375

0.写在前面

  • 本教程使用基于Vue.js 3项目来讲解

1.安装

参考官网安装

yarn add pinia
# or with npm
npm install pinia

2.导入

main.jsmain.ts导入Pinia.js

import { createPinia } from 'pinia'

app.use(createPinia())

3.新建Store

先在src文件夹中创建store文件夹新建index.tsindex.js文件,本教程使用ts

import { ref } from 'vue'
import { defineStore } from 'pinia'


export const useMainStore = defineStore('main', () => {
  // 就像写script setup一样来写store
  const count = ref<number>(1)
  const increment = ():void => {
    count.value++;
  }

  return { count, increment }
})

4.使用Store

App.vue

<template>
  <div>
    count: {{ count }}
    <button @click="increment()">increment</button>
  </div>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/store/index'

// hooks一样来使用
const useMainStore = useMainStore()
const { count, increment } = storeToRefs(useMainStore)

// vue里面也可以直接改
count.value = 0
</script>