vuex的替代者,,可以使用组合式api,,像写每个组件一样,,,没有了之前vuex中mutation,,一个defineStore就是一个模块,,直接引用使用即可,,
比vuex更简洁。。。。
定义数据和函数,,像组件中那样定义就行,,,
如:定义一个counter相关的store,,,defineStore()
定义一个store
import {defineStore} from "pinia";
import {computed, ref} from "vue";
import axios from "axios";// 第一个参数是模块名
export const useCounterStore= defineStore("counter",()=>{const count = ref(0)const doubleCount = computed(()=>count.value*2)const increment = ()=>{count.value++}const list = ref([])const getList = async () => {let res = await axios.get("http://geek.itheima.net/v1_0/channels")console.log(res)list.value = res.data.data.channels}return {count,increment,doubleCount,list,getList}})
引用pinia: 直接对象调用即可,,, 也可以解构出来用,,属性直接解构出来不是响应式,,需要通过storeToRefs()
解构,,,方法不用保证是响应式,直接解构调用即可
<script setup>
import {useCounterStore} from "@/store/counter.js";
import {storeToRefs} from "pinia";const counterStore = useCounterStore()console.log(counterStore)// 直接解构,,响应式会丢失,,,, storeToRef只负责数据相关的处理,没有方法,
const {count,doubleCount} = storeToRefs(counterStore)const {increment} = counterStorecounterStore.getList()</script><template><button @click="increment">{{ count}}</button>
{{ doubleCount }}<div><span v-for="item in counterStore.list" :key="item.id">{{ item.name}}</span></div></template>