在vite+vue3的項目中,當然是可以使用Vuex4的,但是如果讓我選擇的話,我肯定會選pinia,因為簡單又好用,因為之前沒寫過結合TypeScript的使用,是以這篇就來簡單寫一下vite+vue3+ts搭配pinia的基本配置,其實也比較簡單,然後具體使用的話這裡也不細說,會寫一個demo,我之前也寫過一篇關于pinia的使用,大家有興趣可以去看下:vite2 + Vue3中 使用 pinia
首先安裝
npm i pinia
配置相關
① 首先main.ts:
代碼:
import { createApp } from "vue";
import App from "./App.vue";
import store, { key } from "./store";
import router from './router'
import 'element-plus/dist/index.css'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.use(store, key).use(router).use(pinia)
app.mount("#app");
② 然後我們在src下建立store/index.ts 和 store/types.ts
index.ts就是我們管理狀态的一個子產品;
types.ts是我們用來限制對應子產品的狀态的,這裡隻寫了一個,後面如果有新的子產品,可以繼續添加
export type indexType = {
count: number
}
import { defineStore } from 'pinia'
import { indexType } from './types'
export const useIndexStore = defineStore('index', {
state: (): indexType => {
return {
count: 0
}
},
getters: {
doubleCount(): number {
return this.count * 2
}
},
actions: {
updatecount(val: number) {
this.count = val
}
}
})
③ 然後元件中使用
<template>
<h1>count: {{ count }}</h1>
<h1>doubleCount: {{ doubleCount }}</h1>
<el-button type="primary" @click="countChange">更新pinia -> count</el-button>
</template>
<script setup lang="ts">
import { useIndexStore } from '@/pinia'
import { computed } from 'vue'
const indexStore = useIndexStore()
let doubleCount = computed(() => indexStore.doubleCount)
let count = computed({
get(): number {
return indexStore.count
},
set(val:number): void {
indexStore.updatecount(val)
}
})
const countChange = (): void => {
count.value = Math.floor(Math.random() * 10)
}
</script>