[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MuxYBwXS-1646496904674)(https://pinia.vuejs.org/logo.svg#pic_center)]
Vue3 新的发展方向(来源于尤大知乎)
-
Vue 3 将在 2022 年 2 月 7 日 成为新的默认版本
-
基于 Vite 的极速构建工具链
-
<script setup>
带来的开发体验更丝滑的组合式 API 语法 -
Volar 提供的单文件组件 TypeScript IDE 支持
-
vue-tsc 提供的针对单文件组件的命令行类型检查和生成
-
Pinia 提供的更简洁的状态管理
-
新的开发者工具扩展,同时支持
Vue 2/Vue 3
,并且提供一个插件系统来允许社区库自行扩展开发者工具面板。
一、Pinia 简介与基础
1.1 Pinia 简介
- 官方地址:[这里是代码003]
Pinia
是Vuex4
的升级版,也就是Vuex5
Pinia
极大的简化了Vuex
的使用,是Vue3
的新的状态管理工具Pinia
对ts
的支持更好,性能更优, 体积更小,无mutations
,可用于Vue2
和Vue3
Pinia
支持Vue Devtools
、 模块热更新和服务端渲染
1.2 Pinia 基础
Vuex 与 Pinia 对比
Vuex
中核心部分:State
、Getters
、Mutations
(同步) 和Actions
(异步)Pinia
中核心部分:State
、Getters
和Actions
(同步异步均支持)
Pinia 各部分作用
State
: 类似于组件中data
,用于存储全局状态Getters
: 类似于组件中的computed
,根据已有的State
封装派生数据,也具有缓存的特性Actions
: 类似于组件中的methods
,用于封装业务逻辑,同步异步均可以
Pinia 官方示例JS版本
import { defineStore } from 'pinia'
export const todos = defineStore('todos', {
state: () => ({
/** @type {
{ text: string, id: number, isFinished: boolean }[]} */
todos: [],
/** @type {'all' | 'finished' | 'unfinished'} */
filter: 'all',
// type will be automatically inferred to number
nextId: 0,
}),
getters: {
finishedTodos(state) {
// autocompletion! ?
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') {
// call other getters with autocompletion ?
return this.finishedTodos
} else if (this.filter === 'unfinished') {
return this.unfinishedTodos
}
return this.todos
},
},
actions: {
// any amount of arguments, return a promise or not
addTodo(text) {
// you can directly mutate the stat 00e
this.todos.push({ text, id: this.nextId++, isFinished: false })
},
},
})
二、Pinia 在Vue3-Vite中的使用
2.1 基础使用流程
-
① 创建一个
vue vite
项目PS C:UsersFORGETDesktopvue-pinia-demo> npm init vite@latest
Need to install the following packages:
create-vite@latest
Ok to proceed? (y) y
√ Project name: … pinia-demo
√ Select a framework: ? vue
√ Select a variant: ? vue-tsScaffolding project in C:UsersFORGETDesktopvue-pinia-demopinia-demo…
Done. Now run:
cd pinia-demo
npm install
npm run dev
PS C:UsersFORGETDesktopvue-pinia-demo> cd .pinia-demo
PS C:UsersFORGETDesktopvue-pinia-demopinia-demo> npm install -
② 安装
pinia
,-S
是为了将其保存至package.json
中,便于Git
管理给其他人的使用PS C:UsersFORGETDesktopvue-pinia-demopinia-demo> npm install pinia -S
package.json文件中
“dependencies”: {
“pinia”: “^2.0.9”,
“vue”: “^3.2.25”
}, -
③ 创建
pinia
实例并挂载到vue
中// main.ts 文件
import { createApp } from ‘vue’
import App from ‘./App.vue’
import {createPinia} from ‘pinia’
// 创建 Pinia 实例
const pinia = createPinia()
// 创建 Vue 实例
const app