Vue3.5中使用Pina

2024-11-27  本文已影响0人  FrankFang7

Pinia 是一个用于 Vue.js 应用程序的状态管理库,它旨在提供一种更现代、更简洁的方式来管理 Vue 应用的状态。Pinia 的设计灵感来自于 Vuex,但是它更加注重可组合性和 TypeScript 支持。

安装Pinia

npm install pinia
# 或者
yarn add pinia

配置Pinia

/main.js

import './assets/main.css'

import { createApp } from 'vue'
import { createPinia } from 'pinia'

import App from './App.vue'
import router from './router'

const app = createApp(App)

app.use(createPinia())
app.use(router)

app.mount('#app')

创建Store

/src/stores/counter.js

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

// 使用defineStore定义,第一个参数是独一无二的名称
export const useCounterStore = defineStore('counter', () => {
  // 第二个参数可以是Setup函数或 Option 对象,这里是Setup函数。
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  return { count, doubleCount, increment }
})

组件中使用store

/components/MyComponent.vue

<script setup>
// 引入store
import { useCounterStore } from '@/stores/counter'
// 引入响应式函数storeToRefs
import { storeToRefs } from 'pinia'
// 存一下store的函数方法
const counter = useCounterStore()
// 解构引用storeToRefs响应式辅助函数
const { count, doubleCount } = storeToRefs(counter)
// 使用store中的方法
const increment = () => {
  counter.increment()
}
</script>

<template>
  <div>
    <div>count: {{ count }}</div>
    <div>doubleCount: {{ doubleCount }}</div>
    <button @click="increment">Increment</button>
  </div>
</template>

<style>
</style>
上一篇 下一篇

猜你喜欢

热点阅读