您的位置:首页 > 教育 > 培训 > pinia

pinia

2024/10/6 6:52:02 来源:https://blog.csdn.net/qq_36022463/article/details/139813316  浏览:    关键词:pinia

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>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com