-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
state的基础用法 #5
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
前一节我们已经知道了通过store.state来获取状态对象,以及通过store.commit方法触发状态变更。
那么我们在Vue组件中怎么才能获取到状态和修值呢
在Vue组件中获得Vuex状态
这里主要有2点:
1.Vuex 通过 store 选项,提供了一种机制,将状态从根组件“注入”到每一个子组件中①;且子组件能通过 this.$store 访问到store。
2.在vue根实例下的子组件中,通过computed属性读取并返回store中的状态state。computed属性是根据它的依赖自动更新的。所以只要store中的state 发生变化,它就会自动变化。
下面是一个完整的例子:
①[这里想吐槽关于“根组件”和“子组件”具体指的是什么?不过它仅仅是文字上让我产生了歧义,想哔哔的时候再写吧,你不必管它]
mapState 辅助函数
mapState这个辅助函数,它的作用可以理解为一个语法糖,让我们使用简写方法来获取多个状态,下面举例说明:
对象展开运算符
上面的方法四,我们的computed无法一同返回countPlusLocalState状态,其实我们还有办法来解决这个问题。使用对象展开运算符,如果你不了解对象展开运算符是什么,只看官方文档也许会有点懵逼,请先查找资料了解一下,再看下面的例子就会明白了:
我们改写一下方法四
使用对象展开运算符将可以把count,num与 countPlusLocalState混合为一个对象,然后返回给computed。是不是很简单
The text was updated successfully, but these errors were encountered: