关于vue.js:用Setup-API来写Piniajs

7次阅读

共计 754 个字符,预计需要花费 2 分钟才能阅读完成。

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>
正文完
 0