store/index.js
import { defineStore } from "pinia";
import { computed, ref } from "vue";
const useCountStore = defineStore('count',() => {
const count = ref(1)
const addNum = () => {
count.value++
}
const addNumSync = () => {
setTimeout(() => {
count.value++
},1000)
}
const doubleNum = computed(() => {
return count.value * 2
})
return {
count,
addNum,
addNumSync,
doubleNum
}
})
export default useCountStore
// const useCountStore = defineStore('count', {
// state() {
// return {
// count: 1
// }
// },
// actions: {
// addNum() {
// this.count++
// },
// addNumSync() {
// setTimeout(() => {
// this.count++
// }, 1000);
// }
// },
// getters: {
// doubleNum() {
// return this.count * 2
// }
// }
// })
// export default useCountStore
main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App)
// 创建 pinia
const pinia = createPinia()
app.use(pinia)
app.use(router)
app.mount('#app')
组件
<script setup>
import useCountStore from './store';
const countStore = useCountStore()
console.log(countStore)
</script>
<template>
<div>{{ countStore.count }}</div>
<div>{{ countStore.doubleNum }}</div>
<button @click="countStore.addNum">+1</button>
<button @click="countStore.addNumSync">等1s加1</button>
</template>