main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia) //
app.mount('#app')
store/index.js
import { defineStore } from 'pinia'
export const useTestStore = defineStore('test', {
state: () => ({
count: 1,
name: 'yoga',
}),
actions: {
add() {
this.count++
},
},
})
App.vue
<template>
<div>{{ test.count }}</div>
<div>{{ test.name }}</div>
<button @click="add">添加</button>
</template>
<script setup>
import { ref, reactive, provide, getCurrentInstance } from 'vue'
import { useTestStore } from './store'
const test = useTestStore()
console.log(test)
const add = () => {
// 1.可以直接修改
// test.count++
// 2.通过path修改
// test.$patch({
// count: 2,
// })
// 3 path可以传入一个函数
// test.$patch(state => {
// state.count++
// })
// 4 替换state
// test.$state = {
// count: 3,
// }
// 5.通过action修改
test.add()
}
</script>
<style scoped></style>