01pinia

2024-02-11  本文已影响0人  东邪_黄药师

什么是pinia

Pinia 是 Vue 的专属状态管理库,可以实现跨组件或页面共享状态,是 vuex 状态管理工具的替代品,和 Vuex相比,具备以下优势

安装Pinia并注册(min.js)

import { createPinia } from 'pinia'
const app = createApp(App)
// 以插件的形式注册
app.use(createPinia())
app.use(router)
app.mount('#app')

实现counter

1- 定义store
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useCounterStore = defineStore('counter', ()=>{
  // 数据 (state)
  const count = ref(0)

  // 修改数据的方法 (action)
  const increment = ()=>{
    count.value++
  }

  // 以对象形式返回
  return {
    count,
    increment
  }
})
2- 组件使用store
<script setup>
  // 1. 导入use方法
    import { useCounterStore } from '@/stores/counter'
  // 2. 执行方法得到store store里有数据和方法
  const counterStore = useCounterStore()
</script>

<template>
    <button @click="counterStore.increment">
    {{ counterStore.count }}
  </button>
</template>

实现getters

getters直接使用计算属性即可实现

const doubleCount = computed(() => count.value * 2)

调用


image.png 效果.png

异步action

思想:action函数既支持同步也支持异步,和在组件中发送网络请求写法保持一致
步骤:

  1. store中定义action
  2. 组件中触发action
1- store中定义action
const API_URL = 'http://baidu.com'

export const useCounterStore = defineStore('counter', ()=>{
  // 数据
  const list = ref([])
  // 异步action
  const loadList = async ()=>{
    const res = await axios.get(API_URL)
    list.value = res.data.data.channels
  }
  
  return {
    list,
    loadList
  }
})
2- 组件中调用action
<script setup>
    import { useCounterStore } from '@/stores/counter'
  const counterStore = useCounterStore()
  // 调用异步action
  counterStore.loadList()
</script>

<template>
    <ul>
    <li v-for="item in counterStore.list" :key="item.id">{{ item.name }}</li>
  </ul>
</template>
image.png

v

storeToRefs保持响应式解构

直接基于store进行解构赋值,响应式数据(state和getter)会丢失响应式特性,使用storeToRefs辅助保持响应式


image.png
image.png
<script setup>
  import { storeToRefs } from 'pinia'
    import { useCounterStore } from '@/stores/counter'
  const counterStore = useCounterStore()
  // 使用它storeToRefs包裹之后解构保持响应式
  const { count } = storeToRefs(counterStore)

  const { increment } = counterStore
  
</script>

<template>
    <button @click="increment">
    {{ count }}
  </button>
</template>
上一篇下一篇

猜你喜欢

热点阅读