vue3-Pinia

1.什么是pinia

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

1.提供了更加简单的API(去掉了mutation)
2.提供符合组合式风格的API(和Vue3新语法统一)
3.去掉了modules的概念,每一个store都是一个独立的模块
4.搭配TypeScript一起使用提供可靠的类型判断

2.添加pinia到vue项目

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

3.store

store (如 Pinia) 是一个保存状态和业务逻辑的实体,它并不与你的组件树绑定。换句话说,它承载着全局状态。它有点像一个永远存在的组件,每个组件都可以读取和写入它。它有三个概念,state、getter 和 action,我们可以假设这些概念相当于组件中的 data、 computed 和 methods。

(1)定义store
//导入一个方法defineStore
import {defineStore} from 'pinia'
import {ref} from 'vue'

export const useCountStore = defineStore('counter',()=>{
  //定义数据state
  const count = ref(0)
  //定义修改数据的方法(action 同步+异步)
  const increment = () => {
    count.value++
  }
  //getter定义
  const doubleCount = computed(()=> count.value*2)
  //定义异步action
  const list = ref([])
  const getList = async() => {
  const res = await axios.get(API_URL)
  list.value = res.data.data.channels
  }
  //以对象方式return供组件使用
  return {
  count,
  increment
)
(2)使用store
<script setup>
//1.导入use打头的方法
import {useCounterStore} from '@/stores/counter'
//2.执行方法得到store实例对象
const counterStore = useCounterStore()
onMounted(()=>{
  counterStore.getList()
})
</script>
<template>
  <button @click='counterStore.increment'>{{counterStore.count}}</button>
  {{counterStore.doubleCount}}
  <ul>
    <li v-for='item in counterStore.list' :key='item.id'>{{item.name}}</li>
  <ul>
</template>

3. storeToRefs

<script setup>
//1.导入use打头的方法
import {useCounterStore} from '@/stores/counter'
import {storeToRefs} from 'vue'
//2.执行方法得到store实例对象
const counterStore = useCounterStore()
//方法包裹(保持响应式更新)
const {count,doubleCount} = storeToRefs(counterStore)
//方法直接从原来的counterStore中解构赋值
const {increment} = counterStore
onMounted(()=>{
  counterStore.getList()
})
</script>
<template>
  <button @click='increment'>{{count}}</button>
  {{doubleCount}}
  <ul>
    <li v-for='item in counterStore.list' :key='item.id'>{{item.name}}</li>
  <ul>
</template>
  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值