MST

星途 面试题库

面试题:Vue中Pinia基于Composition API状态管理库的基础使用

在Vue项目中使用Pinia基于Composition API创建一个简单的状态管理模块,包含一个计数器(count),实现计数的增加和减少功能,并在组件中使用该状态。请写出具体代码。
19.8万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

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 的方法 incrementdecrement
  • 然后在组件中引入并使用 useCounterStore 获取存储实例,并在模板中展示 count 的值,通过按钮点击调用 incrementdecrement 方法来实现计数的增加和减少。