目录
使用数据
选项式APi
getters中可以直接使用this,来获取state中的数据,也可以通过参数获取
counter.ts
import {defineStore} from 'pinia'
export const useCounterStore = defineStore('counter',{
state:()=>(
{
count:2,
sum:1
}
),
// state() {
// return{
// count:0,
// sum:2,
// school:"121"
// }
// },
getters:{
bigSum:state=>state.sum*10,
double(state){
return state.count*2
},
double2():number{
return this.count*2
}
}
})
组合式API
官方推荐用hooks那种命名方式来给store命名:const useCounterStore = defineStore()
src/store/counter.js
import { defineStore } from "pinia";
import { computed, ref } from "vue";
export const useCounterStore = defineStore("counter",()=>{
//声明数据 state - count
const count = ref(100)
//声明操作数据的方案 action (普通函数)
function addCount(){
if(count.value<1000){
count.value++
}
}
function subCount(){
count.value--
}
//声明基于数据派生的计算属性 getters
const double = computed(() => count.value*2)
//声明数据 state -msg
const msg = ref('你好 pinia')
return {
count,
double,
addCount,
subCount,
msg
}
})
根组件
<script setup>
import Son1Com from '@/components/Son1Com.vue';
import Son2Com from '@/components/Son2Com.vue';
import {useCounterStore} from '@/store/counter'
const counterStore = useCounterStore()
//counterStore是reactive对象 count是ref对象
//reactive包裹的ref不需要 .value来取值
//比如
/*
let haha = reactive({
name:"",
age:ref(0)
})
console.log(haha.age)
*/
console.log(counterStore.count)
</script>
<template>
<h3>
APP.vue根组件
<br>
{{ counterStore.count }}
<br>
{{ counterStore.msg }}
</h3>
<Son1Com></Son1Com>
<Son2Com></Son2Com>
</template>
子组件
<script setup>
import { userCounterStore } from '@/store/counter'
const counterStore = useCounterStore()
</script>
<template>
<div>Son2 {{ counterStore.count }} - {{ counterStore.double }}</div>
<button @click="counterStore.subCount">-</button>
</template>
修改数据
修改数据有三种方式:
import { userCounterStore } from '@/store/counter'
const counterStore = useCounterStore()
//第一种修改方式:直接修改
counterStore.count = 1
//第二种修改方式:$path,可以单个修改,也可以批量修改
counterStore.$patch({
count:100
})
//第三种修改方式:借助action,可以传参
counterStore.addCount()
监视变化:订阅——$subscribe
<script setup lang="ts">
import {useLoveTalkStore} from '@/stores/loveTalk'
const talkstore = useLoveTalkStore()
// const {talkList}= storeToRefs(talkstore)
//订阅:监视store中的数据修改
talkstore.$subscribe((mutate,state)=>{
//mutate:本地修改的信息 state:真正的数据
console.log('talkstore里面保存的数据发生了变化',mutate,state)
localStorage.setItem('talkList',JSON.stringify(state.talkList))
})
</script>
<template>
<div></div>
</template>
<style lang="scss" scoped></style>
import {defineStore} from 'pinia'
export const useLoveTalkStore = defineStore('loveTalk',{
state:()=>(
{
talkList:JSON.parse(localStorage.getItem('talkList') as string) || []//. as string ts的断言
}
),
actions:{
getTalkList(val:Array<string>){
this.talkList = val
}
}
})
//组合式
/*import {ref} from 'vue'
export const useLoveTalkStore = defineStore('loveTalk',()=>{
const talkList = ref([{}])
function getTalkList(){
talkList.value = []
}
return {
talkList,
getTalkList
}
})*/