MST

星途 面试题库

面试题:Vue中Pinia相较于Vuex在基础使用上的简化体现在哪些方面

在Vue开发中,阐述Pinia相比于Vuex,在定义store、获取状态以及提交修改等基础操作上,是如何实现更简洁的状态管理的。举例说明两者在这些方面不同的写法。
41.3万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试

定义store

  • Vuex
    • 需要创建一个 store 实例,定义 statemutationsactions 等模块。例如:
// store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++
    }
  },
  actions: {
    incrementAsync({ commit }) {
      setTimeout(() => {
        commit('increment')
      }, 1000)
    }
  }
})

export default store
  • Pinia
    • 使用 defineStore 函数定义一个 store。例如:
// store.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => ({
    count: 0
  }),
  actions: {
    increment() {
      this.count++
    },
    incrementAsync() {
      setTimeout(() => {
        this.increment()
      }, 1000)
    }
  }
})
  • Pinia 中没有 mutations 的概念,直接在 actions 中修改 state,写法更简洁。

获取状态

  • Vuex
    • 在组件中通过 this.$store.state 获取状态。例如在一个 Vue 组件中:
<template>
  <div>
    {{ $store.state.count }}
  </div>
</template>

<script>
export default {
  name: 'MyComponent'
}
</script>
  • 也可以使用 mapState 辅助函数进行批量映射:
<template>
  <div>
    {{ count }}
  </div>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'MyComponent',
  computed: {
   ...mapState(['count'])
  }
}
</script>
  • Pinia
    • 在组件中通过调用定义的 useStore 函数获取状态。例如:
<template>
  <div>
    {{ counterStore.count }}
  </div>
</template>

<script>
import { useCounterStore } from './store'

export default {
  name: 'MyComponent',
  setup() {
    const counterStore = useCounterStore()
    return { counterStore }
  }
}
</script>
  • Pinia 的获取方式更直接,不需要通过全局的 $store 对象,更符合组合式 API 的风格。

提交修改

  • Vuex
    • 通过 commit 提交 mutations 来修改 state。例如在组件中:
<template>
  <div>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  methods: {
    increment() {
      this.$store.commit('increment')
    }
  }
}
</script>
  • 如果是异步操作,需要通过 dispatch 触发 actionsactionscommit mutations
  • Pinia
    • 直接调用 actions 方法来修改 state。例如:
<template>
  <div>
    <button @click="counterStore.increment">Increment</button>
  </div>
</template>

<script>
import { useCounterStore } from './store'

export default {
  name: 'MyComponent',
  setup() {
    const counterStore = useCounterStore()
    return { counterStore }
  }
}
</script>
  • Pinia 不需要显式的 commit 操作,直接调用 actions 方法即可修改 state,操作更加简洁直观。