面试题答案
一键面试1. 创建 Pinia 状态管理模块
首先在 src/store
目录下创建一个文件,例如 counter.js
:
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const increment = () => {
count.value++
}
const decrement = () => {
count.value--
}
return {
count,
increment,
decrement
}
})
2. 在组件中使用该状态
在 Vue 组件中使用上述状态管理模块,例如 Counter.vue
:
<template>
<div>
<p>Count: {{ counterStore.count }}</p>
<button @click="counterStore.increment">Increment</button>
<button @click="counterStore.decrement">Decrement</button>
</div>
</template>
<script setup>
import { useCounterStore } from '@/store/counter'
const counterStore = useCounterStore()
</script>
在上述代码中:
- 首先使用
defineStore
定义了一个名为counter
的 Pinia 存储模块,其中包含一个响应式数据count
,以及两个修改count
的方法increment
和decrement
。 - 然后在组件中引入并使用
useCounterStore
获取存储实例,并在模板中展示count
的值,通过按钮点击调用increment
和decrement
方法来实现计数的增加和减少。