vue3组合式+pinia使用

92 阅读1分钟

安装

npm install pinia

挂载

//main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.mount('#app')

定义 store数据--直接用 Setup Store方式定义

//默认规则 defineStore 第一个参数是一个独一无二的值,该store以use开头,以store结尾
import { defineStore } from "pinia"
import {ref,computed} from "vue"
export const useCounterStore = defineStore('counter', ()=>{
    const count = ref(0)
    function increment() {
        count.value++
    }
    const count2=computed(()=>count.value*2)
    return { count,count2, increment }
})

组件中基本使用

//响应式数据直接结构会丢失响应式,要用storeToRefs包裹侠,action单独拿
import { useCounterStore } from '../pinia/counter';
const store = useCounterStore()
const {count,count2}=storeToRefs(store)
const increment=store.increment