Vuex中使用mapState对比mapGetters是否具备优势?为何不为site属性创建mapGetter方法?
Hey there! Let's unpack your two questions about the Vuex code you found in that Vue component. I've worked with Vue and Vuex across dozens of projects, so this is a super common pattern I run into all the time.
1. What are the advantages of using mapState over mapGetters (and vice versa)?
First, let's break down what each tool is built for:
mapStateis designed for direct, raw access to Vuex state values. Its biggest advantage is simplicity—you don’t need to write any extra getter functions in your store when all you want is to pull a state property directly into your component. It’s perfect for straightforward reads where you don’t need to transform, filter, or compute the value.mapGettersis for accessing Vuex getters, which are functions that wrap logic around state values. Its key strengths are:- Reusability: If multiple components need the same transformed state value, you define the logic once in a getter instead of repeating it across components.
- Caching: Vuex automatically caches getter results. A getter only re-runs if the state properties it depends on change, which is a big win for performance with complex calculations.
- Encapsulation: Getters let you hide the structure of your state from components. If you later refactor your state’s shape, you only need to update the getter instead of every component that uses that value.
In short: Use mapState for simple, no-frills state access; use mapGetters when you need computed, reusable logic around state values.
2. Why use mapState for site instead of a getter like getRouteName?
Looking at your code snippet:
computed: { ...mapState('settings', { site: state => state.general.site }), ...mapGetters('settings', [ 'getRouteName' ]) }
The arrow function here is just mapState’s way of letting you customize the mapping—you’re telling Vuex, "Pull state.general.site from the settings module and call it site in this component."
The reason they didn’t use a getter for site is probably there’s no need for extra logic. The site value is just a direct nested property from state, so creating a getter like getSite: state => state.general.site would be redundant. Using mapState with the arrow function is more concise here—it lets you skip defining an unnecessary getter in the store.
If later on you need to do something with site (like format it, combine it with another state value, or add validation), you could easily refactor it into a getter and switch to mapGetters. But for now, the mapState approach is the simplest solution for the current requirement.
内容的提问来源于stack exchange,提问作者mcool




