Pinia(vuex)基本介绍

212 阅读4分钟

Pinia

基本介绍

Pinia 是 Vue.js 的轻量级状态管理库

官方网站:pinia.vuejs.org/

pinia核心概念

  • state: 状态
  • getters: 计算属性
  • actions: 修改状态(包括同步和异步,pinia中没有mutations)

基本使用

目标:掌握pinia的使用步骤

(1)安装

yarn add pinia
# or
npm i pinia

(2)在main.js中挂载pinia

import { createApp } from 'vue'
import App from './App.vue'import { createPinia } from 'pinia'const app = createApp(App)
app.use(createPinia())
app.mount('#app')

选项式 Store

state 的使用

新建文件 store/counter.js

import { defineStore } from 'pinia'
// 创建store,命名规则: useXxxxStore
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  }
})
​
export default useCounterStore

(4) 在组件中使用

<script setup>
import useCounterStore from './store/counter'const counter = useCounterStore()
</script><template>
  <h1>根组件---{{ counter.count }}</h1>
</template><style></style>

actions的使用

目标:掌握pinia中actions的使用

在pinia中没有mutations,只有actions,不管是同步还是异步的代码,都可以在actions中完成。

(1)在actions中提供方法并且修改数据

import { defineStore } from 'pinia'
// 1. 创建store
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})
​
export default useCounterStore

(2)在组件中使用

<script setup>
import useCounterStore from './store/counter'const counter = useCounterStore()
</script><template>
  <h1>根组件---{{ counter.count }}</h1>
  <button @click="counter.increment">加1</button>
  <button @click="counter.incrementAsync">异步加1</button>
</template>

getters的使用

pinia中的getters和vuex中的基本是一样的,也带有缓存的功能

(1)在 getters 中提供计算属性,如果需要修改请写在 actions

import { defineStore } from 'pinia'
// 1. 创建store
// 参数1:store的唯一表示
// 参数2:对象,可以提供state actions getters
const useCounterStore = defineStore('counter', {
  state: () => {
    return {
      count: 0,
    }
  },
  getters: {
    double() {
      return this.count * 2
    },
  },
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.count++
      }, 1000)
    },
  },
})
​
export default useCounterStore
​

(2)在组件中使用

<h1>根组件---{{ counter.count }}</h1>
<h3>{{ counter.double }}</h3>

组合式 Store

基本使用

  • 创建 Store
import { defineStore } from "pinia"
import { computed, ref } from "vue"export const useCounterStore = defineStore("counter", () => {
    
  return { }
})
<script setup>
import { useCounterStore } from "./store/counter"
// store中有状态和函数
const store = useCounterStore()
</script>
  • 进行状态管理
import { defineStore } from "pinia"
import { computed, ref } from "vue"export const useCounterStore = defineStore("counter", () => {
  // state
  const count = ref(100)
  // getters
  const doubleCount = computed(() => count.value * 2)
  // mutations
  const update = () => count.value++
  // actions
  const asyncUpdate = () => {
    setTimeout(() => {
      count.value++
    }, 1000)
  }
  return { count, doubleCount, update, asyncUpdate }
}) 
<template>
  APP {{ store.count }} {{ store.doubleCount }}
  <button @click="store.update()">count++</button>
  <button @click="store.asyncUpdate()">async update</button>
</template>

对比总结

  • 通过 const useXxxStore = defineStore('id',函数) 创建仓库得到使用仓库的函数
VuexPinia
staterefreactive创建的响应式数据
gettercomputed 创建的计算属性
mutations 和 actions普通函数,同步异步均可
  • 使用Pinia与在组件中维护数据大体相同,这就是 Pinia 的状态管理基本使用

storeToRefs 辅助函数

目标:掌握storeToRefs的使用

如果直接从 pinia 中解构数据,会丢失响应式, 使用storeToRefs可以保证解构出来的数据也是响应式的

<script setup>
import { storeToRefs } from 'pinia'
import useCounterStore from './store/counter'const counter = useCounterStore()
// 如果直接从pinia中解构数据,会丢失响应式
const { count, double } = counter
​
// 使用storeToRefs可以保证解构出来的数据也是响应式的
const { count, double } = storeToRefs(counter)
</script>

pinia 模块化

在复杂项目中,不可能把所有数据都定义到一个 store 中,Pinia 支持定义多个 Store 模块

一般来说会一个模块对应一个store,最后通过一个根 store 进行整合

(1)新建store/user.js文件

import { defineStore } from 'pinia'const useUserStore = defineStore('user', {
  state: () => {
    return {
      name: 'zs',
      age: 100,
    }
  },
})
​
export default useUserStore
​

(2)新建store/index.js

import { defineStore } from 'pinia'
import useUserStore from './user'
import useCounterStore from './counter'// 封装主Store,把独立的模块做统一管理,方便开发时使用
const useMainStore = defineStore('main', {
  state: () => ({
    user: useUserStore(),
    counter: useCounterStore()
  }),
})
​
export default useMainStore

(3)在组件中使用

<script setup>
import { storeToRefs } from 'pinia'
import useMainStore from './store'
// counter 本身存储的就是 reactive Store 可以直接解构使用
const { counter } = useMainStore()
​
// 使用storeToRefs可以保证解构出来的数据也是响应式的
const { count, double } = storeToRefs(counter)
</script>

Pinia 综合案例-todomvc

列表展示功能

(1) 在main.js中引入pinia

import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import './styles/base.css'
import './styles/index.css'const pinia = createPinia()
createApp(App).use(pinia).mount('#app')
​

(2)新建文件 store/modules/todos.js

import { defineStore } from 'pinia'
​
const useTodosStore = defineStore('todos', {
  state: () => ({
    list: [
      {
        id: 1,
        content: '吃饭',
        done: false,
      },
      {
        id: 2,
        content: '睡觉',
        done: true,
      },
      {
        id: 3,
        content: '打豆豆',
        done: false,
      },
    ],
  }),
})
​
export default useTodosStore
​

(3)新建文件store/index.js

import useTodosStore from './modules/todos'export default function useStore() {
  return {
    todos: useTodosStore(),
  }
}
​

(4)在src/components/TodoMain.vue中渲染

<script setup>
import useStore from '../store'const { todos } = useStore()
</script><template>
  <section class="main">
    <input id="toggle-all" class="toggle-all" type="checkbox" />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <li
        :class="{ completed: item.done }"
        v-for="item in todos.list"
        :key="item.id"
      >
        <div class="view">
          <input class="toggle" type="checkbox" :checked="item.done" />
          <label>{{ item.content }}</label>
          <button class="destroy"></button>
        </div>
        <input class="edit" value="Create a TodoMVC template" />
      </li>
    </ul>
  </section>
</template>

修改任务状态

目标:完成任务修改状态

(1)在 actions 中提供方法

actions: {
  changeDone(id) {
    const todo = this.list.find((item) => item.id === id)
    todo.done = !todo.done
  },
},

(2)在组件中注册事件

<input
  class="toggle"
  type="checkbox"
  :checked="item.done"
  @click="todos.changeDone(item.id)"
/>

删除任务

目标:完成任务删除功能

(1)在actions中提供方法

actions: {
  delTodo(id) {
    this.list = this.list.filter((item) => item.id !== id)
  },
},

(2)在组件中注册事件

<button class="destroy" @click="todos.delTodo(item.id)"></button>

添加任务

目标:完成任务添加功能

(1)在actions中提供方法

actions: {
  addTodo(content) {
    this.list.unshift({
      id: Date.now(),
      content,
      done: false,
    })
  },
},

(2)在组件中注册事件

<script setup>
import { ref } from 'vue'
import useStore from '../store'
const { todos } = useStore()
const content = ref('')
const add = () => {
  // 1. 非空检验
  if (content.value === '') {
    return alert('请输入内容~')
  }
  // 2. 添加到列表中
  todos.addTodo(content.value)
  // 3. 清空输入框
  content.value = ''
}
</script><template>
  <header class="header">
    <h1>todos</h1>
    <input
      class="new-todo"
      placeholder="What needs to be done?"
      autofocus
      v-model.trim="content"
      @keyup.enter="add"
    />
  </header>
</template>

全选反选功能

完成todos的全选和反选功能

(1)在getters中提供计算属性,在actions中提供方法

const useTodosStore = defineStore('todos', {
​
  actions: {
    // 全选修改小选
    checkAll(bl) {
      this.list.forEach((item) => {
         item.done = bl
      })
    },
  },
  getters: {
    // 全选计算
    isCheckAll() {
      return this.list.every((item) => item.done)
    },
  },
})

(2)在组件中使用

<input
  id="toggle-all"
  class="toggle-all"
  type="checkbox"
  :checked="todos.isCheckAll"
  @change="todos.checkAll(!todos.isCheckAll)"
/>

底部统计与清空功能

目标:完成底部的统计与清空功能

(1)在getters中提供计算属性

const useTodosStore = defineStore('todos', {
​
  actions: {
    clearTodo() {
      this.list = this.list.filter((v) => !v.done)
    },
  },
  getters: {
    leftCount(state) {
      return state.list.filter((v) => !v.done).length
    },
  },
})
​
​

(2)在组件中使用

<span class="todo-count">
  <strong>{{ todos.leftCount }}</strong> item left
</span><button class="clear-completed" @click="todos.clearTodo">
  Clear completed
</button>

底部筛选功能

(1)提供数据

state: () => ({
  filters: ['All', 'Active', 'Completed'],
  active: 'All',
}),

(2)提供actions

actions: {
​
  changeActive(active) {
    this.active = active
  },
},

(3)在footer中渲染

<ul class="filters">
  <li
    v-for="item in todos.filters"
    :key="item"
    @click="todos.changeActive(item)"
  >
    <a :class="{ selected: item === todos.active }" href="#/">{{ item }}</a>
  </li>
</ul>

(4)提供计算属性

showList() {
  if (this.active === 'Active') {
    return this.list.filter((item) => !item.done)
  } else if (this.active === 'Completed') {
    return this.list.filter((item) => item.done)
  } else {
    return this.list
  }
},

(5)组件中渲染

<ul class="todo-list">
  <li
    :class="{ completed: item.done }"
    v-for="item in todos.showList"
    :key="item.id"
  >

持久化

(1)订阅store中数据的变化

​
todos.$subscribe(() => {
  localStorage.setItem('todos', JSON.stringify(todos.list))
})

(2)获取数据时从本地缓存中获取

state: () => ({
  list: JSON.parse(localStorage.getItem('todos')) || [],
}),

\