Pinia---Vue3最新状态管理库

Pinia是Vue的专属的最新状态管理库,是Vuex状态管理工具的替代品

Pinia: Pinia | Pinia

1. 安装: npm install pinia

2. 创建一个 pinia 实例 (根 store) 并将其传递给应用

// main.js
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
// 1.导入
import { createPinia } from 'pinia'
// 2.执行方法得到实例
const pinia = createPinia()
// 3.把pinia实例加入到app应用中
createApp(App).mount('#app').use(pinia)

3. 定义store

// stores/counters.js
// 导入
import {defineStore} from "pinia";
import {computed, ref} from "vue";
import axios from 'axios'
const API_URL = 'http://geek.itheima.net/v1_0/channels'
export const useCounterStore = defineStore('counter', () => {
    // 定义数据(state)
    const count = ref(0)
    // 定义修改数据的方法(action )-----同步
    const increment = () => {
        count.value++
    }
    //getter定义
    const doubleCount = computed(() => count.value * 2)

    //定义action-----------异步
    const list= ref(0)
    const getList = async ()=>{
        const res = await axios.get(API_URL)
        console.log(res)
        list.value = res.data.data.channels
    }
    // 以对象的方式return供组件使用
    return {count, increment,doubleCount,list,getList}
})

4. 使用store

// 组件
<script setup>
// 1. 导入useCounterStore
import {useCounterStore} from "@/stores/counters";
import {onMounted} from "vue";
import {storeToRefs} from "pinia";
// 2.执行方法得到实例
const counterStore = useCounterStore()
console.log(counterStore)

// 直接解构赋值---------响应式丢失
// const {count,doubleCount} = counterStore

// 使用storeToRefs解构赋值------保持响应式
const {count,doubleCount} = storeToRefs(counterStore)

// 方法直接从原来的counterStore中结构赋值
const {increment} = counterStore

onMounted(()=>{
    counterStore.getList()
})
</script>

<template>
  <!--<button @click="counterStore.increment">{{counterStore.count}}</button><br>-->
  <!--<h2>{{counterStore.doubleCount}}</h2>-->
    <button @click="counterStore.increment">{{count}}</button><br>
    <h2>{{doubleCount}}</h2>
  <ul>
      <li v-for="item in counterStore.list" :key="item.id">{{item.name}}</li>
  </ul>
</template>

注意:上面中

 响应式对象若要解构赋值,不能这样写,---------------------响应式丢失:

// 响应式丢失,视图不在更新
const {count,doubleCount} = countStore

 响应式对象若要解构赋值,可以这样写-------------------保持响应式

import {storeToRefs} from "pinia";

// 使用storeToRefs解构赋值------保持响应式
const {count,doubleCount} = storeToRefs(counterStore)

 方法若要解构赋值,需要这样写

// 方法直接从原来的counterStore中结构赋值
const {increment} = counterStore

Pinia中不需要mutation了,action既支持同步,也支持异步

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值