跳到主要内容

添加状态管理 Pinia

视频演示

环境准备
  • 安装 Git
    • 设置换行符为 lf
    $ git config --global core.autocrlf input
    $ git config --global core.eol lf
  • 安装 Node.js
  • 安装 VSCode

拉取项目

# 从 GitHub 拉取项目(存在网络限制)
$ git clone --branch v0.0.2 https://github.com/geenln/vue3-elemnt-plus-ts.git

# 或者从 Gitee 拉取项目
$ git clone --branch v0.0.2 https://gitee.com/genin/vue3-elemnt-plus-ts.git

安装项目依赖

$ npm install

启动开发服务器

$ npm run dev

添加状态库 Pinia

安装 Pinia

$ npm install pinia

创建文件 src/store/index.ts

src/store/index.ts
import {createPinia} from 'pinia'

const pinia = createPinia()

export default pinia

更新文件 src/main.ts

src/main.ts
import {createApp} from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
+import pinia from './store'

const app = createApp(App)
app.use(router)
+app.use(pinia)
app.mount('#app')

Pinia 状态管理示例

创建文件 src/store/modules/counter.ts

src/store/modules/counter.ts
import {defineStore} from 'pinia'

export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
getters: {
doubleCount: state => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})

更新文件 src/App.vue

src/App.vue
<script setup lang="ts">
+import {useCounterStore} from '@/store/modules/counter'

+const counterStore = useCounterStore()
</script>

<template>
<h1>Vue3 Element Plus Ts</h1>
+ <button class="border p-2 rounded-md" @click="counterStore.increment()">
+ count加1
+ </button>
+ <div class="flex gap-2">
+ <span>{{ counterStore.count }}</span>
+ <span>{{ counterStore.doubleCount }}</span>
+ </div>

<div class="flex gap-2">
<RouterLink to="/t1" class="underline text-teal-600">TestA.vue</RouterLink>
|
<RouterLink to="/t2" class="underline text-teal-600">TestB.vue</RouterLink>
</div>
<RouterView />
</template>