Vue3.0 使用Pinia

发布于:2024-12-07 ⋅ 阅读:(165) ⋅ 点赞:(0)

下面是一个使用Vue 3、Pinia和TypeScript的简单示例,这个示例创建了一个计数器应用。

步骤 1: 创建Vue 3项目
如果你还没有创建项目,可以使用Vue CLI或Vite来创建一个新项目,并选择TypeScript。

使用Vue CLI创建项目:

bash
vue create my-pinia-project
在创建过程中选择TypeScript。

或者,使用Vite创建项目:

bash
npm create vite@latest my-pinia-project – --template vue-ts
步骤 2: 安装Pinia
在项目目录中,安装Pinia:

bash
npm install pinia
步骤 3: 配置Pinia
在项目的入口文件(如main.ts)中,配置Pinia:

typescript
// main.ts
import { createApp } from ‘vue’;
import { createPinia } from ‘pinia’;
import App from ‘./App.vue’;

const app = createApp(App);

app.use(createPinia());
app.mount(‘#app’);
步骤 4: 创建Pinia Store
创建一个Pinia store来管理状态:

typescript
// stores/counter.ts
import { defineStore } from ‘pinia’;

export const useCounterStore = defineStore(‘counter’, {
state: () => ({
count: 0,
}),
getters: {
doubleCount: (state) => state.count * 2,
},
actions: {
increment() {
this.count++;
},
decrement() {
this.count–;
},
},
});
步骤 5: 在组件中使用Store
在Vue组件中使用Pinia store:

vue

Count: {{ counter.count }}

Double Count: {{ counter.doubleCount }}

这个示例创建了一个名为useCounterStore的store,其中包含一个名为count的状态,一个计算属性doubleCount,以及两个actions:increment和decrement。在组件中,我们导入并使用这个store,通过调用increment和decrement来更新计数,并通过count和doubleCount显示当前计数和其两倍的值。

现在,你可以运行你的Vue应用,并通过点击按钮来增加或减少计数。这个简单的示例展示了如何在Vue 3项目中使用Pinia和TypeScript来管理状态。

以上就是文章全部内容了,如果喜欢这篇文章的话,还希望三连支持一下,感谢!