引用pinia: 直接对象调用即可,,, 也可以解构出来用,,属性直接解构出来不是响应式,,需要通过

csdn推荐

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} = counterStore
counterStore.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>

文章来源:https://blog.csdn.net/qq_36022463/article/details/139813316



微信扫描下方的二维码阅读本文

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容