在App.vue中,写
<template>
<div>
<h1>{{ count }}</h1> <!-- mainStore.$state.count mainStore.count -->
<h1>{{ name }}</h1>
<h1>{{ fullName }}</h1>
<button @click="add">按钮自增10</button>
</div>
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { useMainStore } from './store'
const mainStore = useMainStore()
// 不要轻易解构响应式对象
const {count,name,fullName} = storeToRefs(mainStore)
function add(){
mainStore.addCount(10)
}
</script>
在main.js中,写
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
在store文件夹的index.js文件,其中写
import {defineStore} from 'pinia'
import {ref} from 'vue'
// 选项式API
// const useMainStore = defineStore('main',{
// state:()=>{
// return{
// count:0,
// name:'peiqi'
// }
// },
// actions:{
// addCount(number){
// //this.count += number
// setTimeout(()=>{
// this.count += number
// },1000)
// }
// },
// getters:{
// fullName(){
// return '小猪' + this.name
// }
// }
// })
// 组合式API
const useMainStore = defineStore('main',()=>{
const count = ref(0)
const addCount = ()=>{
count.value++
}
return{
count,
addCount
}
})
export {useMainStore}
PS:1.pnpm i pinia;2.useXXXXX是用于常见实例的命名方式;3.Vue2是选项式API,Vue3是组合式API