在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>