Pinia
counter.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'export const useCounterStore = defineStore('counter', () => {const count = ref(0)const doubleCount = computed(() => count.value * 2)const name = ref('张三')const age = ref(18)const books = ref([{name: 'Vue',number: 10},{name: 'HTML',number: 20}])function increment() {count.value++age.value++}function decrement() {count.value--age.value--}return {count,doubleCount,name,age,books,increment,decrement}
})
test.vue
<template><div class="hello-page"><div>{{ count }}</div><div>{{ store.doubleCount }}</div><div>{{ age }}</div><div>{{ store.name }}</div><div v-for="item in store.books" :key="item.name"><span>{{ item.name }}:</span><span>{{ item.number }}本</span></div><el-button @click="increment"> + </el-button><el-button @click="store.decrement"> - </el-button><el-button @click="handlePatch1">变更1</el-button><el-button @click="handlePatch2">变更2</el-button><el-button @click="goDetail">detail</el-button></div>
</template><script setup>
import { ref, computed } from 'vue'
import { useCounterStore } from '@/store/counter'
import { storeToRefs } from 'pinia'
import router from '@/router/index.js'/*** 1. 可以通过 store 实例访问 state,对其进行读写。(新的属性如果没有在 state() 中被定义,则不能被添加。它必须包含初始状态。)* 2. 需要使用storeToRefs(),从 store 中提取属性时保持其响应性。* 3. 可以直接从 store 中解构 action* 4. 以调用 $patch 方法,在同一时间更改多个属性*/
const store = useCounterStore()
const { count } = storeToRefs(store)
const { increment } = store
const age = computed(() => store.age)// 变更
const handlePatch1 = () => {store.$patch({count: 10,name: '王五'})
}// 变更
const handlePatch2 = () => {store.$patch((state) => {state.books.push({name: 'CSS',number: 18})state.age = 30})
}const goDetail = () => {store.name = '李四'router.push({path: '/detail'})
}// 订阅 state:比起普通的 watch(),使用 $subscribe() 的好处是 subscriptions 在 patch 后只触发一次
store.$subscribe((mutation, state) => {console.log(mutation, state)
})store.$onAction(({name, // action 名称store, // store 实例,类似 `someStore`args, // 传递给 action 的参数数组after, // 在 action 返回或解决后的钩子onError, // action 抛出或拒绝的钩子
}) => {// 为这个特定的 action 调用提供一个共享变量const startTime = Date.now()// 这将在执行 "store "的 action 之前触发。console.log(`Start "${name}" with params [${args.join(', ')}].`)console.log(store.count)// 这将在 action 成功并完全运行后触发。// 它等待着任何返回的 promiseafter((result) => {console.log('finished: ', store.count)})// 如果 action 抛出或返回一个拒绝的 promise,这将触发onError((error) => {console.warn(`Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`)})
})</script><style lang="scss" scoped>
.hello-page {width: 1000%;height: 100%;padding: 10px;
}
</style>