为什么状态对组件可见? [英] why is state visible to components?

查看:32
本文介绍了为什么状态对组件可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,vuex 的重点是保证状态的一致性,只通过突变/操作/获取器将其暴露给组件.

As I understand, the point of vuex is to guarantee the consistency of state, by exposing it to components only through mutations/actions/getters.

然而,组件可以直接操作 $store.state 而不使用突变/动作 - 可能会使状态不一致.

However, components can directly manipulate $store.state without using mutations/actions - potentially making the state inconsistent.

为什么要直接暴露vuex状态?

Why is vuex state exposed directly?

推荐答案

使用突变/动作/getter 等是建议的最佳实践,但并不意味着它必须被遵循.

Using mutations / actions / getters etc is a suggested best practice but doesn't mean it has to be followed.

可能是您只想从状态中读取一个值,此时为它编写一个 getter 可能有点过头了.

It could be that you just want to read a value from the state at which point it might be a little over-kill to write a getter for it.

我个人总是尝试使用 action/getter 来保持一致,因为当你开始在没有中心化系统的情况下改变状态时,它会变得混乱.

I personally always try to use actions / getters to keep things consistent as it can get messy when you start mutating the state without a centralised system.

举个例子,如果你在状态中有一个 user 模块.您可能只需要用户名,所以 $store.state.user.username 但我总是更喜欢通过 getUser 公开用户并通过以下方式在组件上访问它user.username.

An example would be if you had a user module in the state. You might be tempted to just need the username so $store.state.user.username but I would always prefer to expose the user via getUser and access it on the component via user.username.

能够直接访问状态的专业人士是手表:

A pro for being able to access the state directly is a watch:

watch: {
  '$store.state.user' (to, from) {
    console.log('I changed!')
  }
}

这将让您知道用户状态何时发生变化,但同样,如果您使用 $this.$store.dispatch('setUser', myUser) 您可以在操作中执行相同操作.

This would allow you to know whenever the user state changed but again, if you used $this.$store.dispatch('setUser', myUser) you could do the same in the action.

我认为这里的关键是保持一致,选择一种方法并使用它,但始终建议遵循最佳实践.

I think the key here is be consistent, pick a way and use it but following best practice is always recommended.

这篇关于为什么状态对组件可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆