TypeScript和Pinia:为你的Vue应用注入灵魂
warning:
这篇文章距离上次修改已过186天,其中的内容可能已经有所变动。
import { defineStore } from 'pinia'
// 定义一个名为'counter'的store
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++
},
},
})
// 在Vue组件中使用store
import { useCounterStore } from './counterStore'
export default {
setup() {
// 创建store实例
const counterStore = useCounterStore()
// 使用store中的action
function incrementCounter() {
counterStore.increment()
}
return {
counterStore,
incrementCounter,
}
},
}
这个例子展示了如何在Vue应用中使用TypeScript和Pinia创建一个简单的计数器store,并在Vue组件中使用它。首先定义了一个名为counter
的store,包含一个状态count
和一个操作increment
。然后在Vue组件的setup
函数中,通过调用useCounterStore
来创建store的实例,并使用incrementCounter
函数来触发increment
操作。
评论已关闭