源码
store\count.ts
import {defineStore} from 'pinia'
//因为当前演示项目中,有一个 count组件,所以当前文件名也起名为 count.ts
//官方推荐我们使用 Hooks 命名思想: use***Store, 表示 使用和...有关的store
//useCountStore() 是一个 Store 定义函数(工厂函数)
//此处∈ 选项式语法(Options API)
// 第0个参数:store 名称(字符串)
// 第1个参数:选项对象
export const useCountStore = defineStore('count',{ //配置对象
//增加 actions , 里面放置的是一个一个的方法,用于响应组件中的动作。
actions:{
increment(value){
console.log('increment被调用了,value=',value)
//修改数据:
//console.log(this.sum) //this是当前的store,即 useCountStore
this.sum += value
}
},
//state 必须写为一个函数,并返回一个对象。
// 真正存储数据的地方
state(){
return {
sum:6,
school: 'softool',
address: '中国'
}
}
})components\Count.vue
<template>
<div class="count">
<!--h2>当前求和为:{{ sum }}</h2-->
<h2>当前求和为:{{ countStore.sum }}</h2>
<h3>欢迎来到: {{ countStore.school }}, 坐落于: {{ countStore.address }}</h3>
<!-- 将从 select 收集到内容 转为数字(.number) 给 n -->
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button @click="add">加</button>
<button @click="minus">减</button>
</div>
</template>
<script setup lang="ts" name="Count">
import { ref } from "vue";
//使用Pinia的步骤:
// 第0步 引入自定义的 useCountStore()方法
import {useCountStore} from '@/store/count'
import { count } from "console";
// 第1步 创建 useCountStore() 的实例为 countStore
//使用 useCountStore(), 实例化得到一个专门保存 count 相关的 store
const countStore = useCountStore()
console.log('@@@,countStore=', countStore) //经测试此时的实例 countStore 是一个 Proxy 定义的响应式对象。
// 以下两种方式都可以拿到state中的数据
// console.log('@@@',countStore.sum)
// console.log('@@@',countStore.$state.sum)
// 数据
//let sum = ref(1) // 当前求和
let n = ref(1) // 用户选择的数字
// 方法
function add(){
//sum.value += n.value
//感受 Pinia 的好处:
//第1种修改方法: 这种写法在 Vuex 中是有问题的,但是在 Pinia 中可以直接修改。
/*countStore.sum += 1
countStore.school = '尚硅谷'
countStore.address = '北京'*/
//第2种修改方法: 批量变更
/*countStore.$patch({ //patch 碎片
sum:888,
school: '尚硅谷',
address: '北京'
})*/
//第3种修改方法: 借助 actions(动作)
countStore.increment(n.value)
}
function minus(){
//sum.value -= n.value
}
</script>
<style scoped>
.count {
background-color: skyblue;
padding: 10px;
border-radius: 10px;
box-shadow: 0 0 10px;
}
select,button {
margin: 0 5px; /*上下为0px 左右间距5px*/
height: 25px;
}
</style>
