1、pinia的概念与自己的理解
pinia主要解决的问题是:不同组件之间可以实现数据共享,定义一个全局变量,不同组件或页面都能使用它,也能对这个变量进行更新修改等操作,同时数据的变化也会同步到其他组件,因为数据是全局共享的。
2、pinia案例分析
1、需要安装pinia
2、在main.js中引用
3、定义一个全局状态
4、在不同组件中使用这个状态
2.1、main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
const app = createApp(App)
app.use(pinia)
app.mount('#app')
2.2 定义一个store文件
这个是官方demo,定义一个todos全局状态,里面有state getters和actions,相当于vue中的data computed和methods。
import { defineStore } from 'pinia'
export const useTodos = defineStore('todos', {
state: () => ({
/** @type {{ text: string, id: number, isFinished: boolean }[]} */
todos: [],
/** @type {'all' | 'finished' | 'unfinished'} */
filter: 'all',
// 类型将自动推断为 number
nextId: 0,
}),
getters: {
finishedTodos(state) {
// 自动补全! ✨
return state.todos.filter((todo) => todo.isFinished)
},
unfinishedTodos(state) {
return state.todos.filter((todo) => !todo.isFinished)
},
/**
* @returns {{ text: string, id: number, isFinished: boolean }[]}
*/
filteredTodos(state) {
if (this.filter === 'finished') {
// 调用其他带有自动补全的 getters ✨
return this.finishedTodos
} else if (this.filter === 'unfinished') {
return this.unfinishedTodos
}
return this.todos
},
},
actions: {
// 接受任何数量的参数,返回一个 Promise 或不返回
addTodo(text) {
// 你可以直接变更该状态
this.todos.push({ text, id: this.nextId++, isFinished: false })
},
},
})
2.3 其他组件如何使用这个全局状态
<script setup>
import { useCounterStore } from './counterStore'
const store = useCounterStore()
</script>
<template>
<p> count is {{ store.todos }}</p>
</template>