在vue中pinia的基本使用
# 在Vue3中使用TypeScript和Pinia
# 1.安装Vue3、TypeScript和Pinia
npm install vue@next typescript pinia
1
# 2.创建Pinia store
在Vue3中,Pinia是一个新的状态管理库。可以创建一个store文件夹,在其中创建一个store.ts文件,来定义Pinia store.
import { defineStore } from 'pinia'
export const useStore = defineStore({
id: 'app',
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 3.在Vue组件中使用Pinia store
要在Vue组件中使用Pinia store,可以使用useStore()函数来获取store实例,并使用computed和methods属性来访问store的状态和操作。
<template>
<div>
<span>{{ count }}</span>
<button @click="increment">Increment</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from './store'
export default defineComponent({
setup() {
const store = useStore()
return {
count: store.count,
increment: store.increment
}
}
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
上次更新: 2023/06/25, 10:06:00