diff --git "a/\345\224\220\345\244\251\345\250\245/20240513-pinia.md" "b/\345\224\220\345\244\251\345\250\245/20240513-pinia.md" new file mode 100644 index 0000000000000000000000000000000000000000..36083029dd601cbfc3c23e32697c333ff08f1497 --- /dev/null +++ "b/\345\224\220\345\244\251\345\250\245/20240513-pinia.md" @@ -0,0 +1,80 @@ +## pinia +下面就是 pinia API 的基本用法 (为继续阅读本简介请确保你已阅读过了开始章节)。你可以先创建一个 Store: + +js +// stores/counter.js +import { defineStore } from 'pinia' + +export const useCounterStore = defineStore('counter', { + state: () => { + return { count: 0 } + }, + // 也可以这样定义 + // state: () => ({ count: 0 }) + actions: { + increment() { + this.count++ + }, + }, +}) + +然后你就可以在一个组件中使用该 store 了: + +vue + + +更真实的示例 +这是一个更完整的 Pinia API 示例,在 JavaScript 中也使用了类型提示。对于某些开发者来说,可能足以在不进一步阅读的情况下直接开始阅读本节内容,但我们仍然建议你先继续阅读文档的其余部分,甚至跳过此示例,在阅读完所有核心概念之后再回来。 + +js +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 }) + }, + }, +}) \ No newline at end of file diff --git "a/\345\224\220\345\244\251\345\250\245/20240516-\345\244\215\344\271\240.md" "b/\345\224\220\345\244\251\345\250\245/20240516-\345\244\215\344\271\240.md" new file mode 100644 index 0000000000000000000000000000000000000000..8ab6db9ca43e8d69f456288874929e74344726b7 --- /dev/null +++ "b/\345\224\220\345\244\251\345\250\245/20240516-\345\244\215\344\271\240.md" @@ -0,0 +1,146 @@ +## 复习代码 +```js + + + + + +``` \ No newline at end of file