In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
这篇文章主要介绍Vuex中的State和Getter有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
Vuex 的内脏由五部分组成:State、Getter、Mutation、Action 和 Module。本篇文章先带大家深入了解一下Vuex中的State和Getter,希望对大家有所帮助!
Vuex_State
Vuex是vue的状态管理工具,为了更方便的实现多个组件共享状态。
安装npm install vuex --save复制代码使用import Vue from 'vue';import Vuex from 'vuex';Vue.use(Vuex);const store = new Vuex.Store({ state: { count: 0 }})new Vue({ store,})State
单一状态树,使用一个对象就包含了全部的应用层级状态。
在Vue组件中获得Vuex状态
Vuex 通过store 选项,提供了一种机制将状态从跟组件"注入"到每一个子组件中(调用Vue.use(Vuex))。
通过在根实例中注册store选项,该store实例会注入到根组件下的所有子组件中,且子组件能通过this.$store访问。
{{ $store.state.count }}复制代码mapState 辅助函数
当一个组件需要获取多个状态时,将这些状态都声明为计算属性会有些重复和冗余。为了解决这个问题,我们可以使用mapState辅助函数帮助我们生成计算属性:
import { mapState } from 'vuex';computed: { ...mapState(['count']),},
使用不同的名字:
computed: { ...mapState({ storeCount: state => state.count, // 简写 storeCount: 'count', // 等同于 state => state.count }),},Vuex_Getter
store的计算属性。getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
Getter 接收state作为其第一个参数、getters作为其第二个参数。
getters: { doubleCount (state) { return state.count * 2; }}通过属性访问
Getter会暴露为store.getters对象:this.$store.getters.doubleCount
通过方法访问
也可以让getter返回一个函数,来实现给getter传参
getters: { addCount: state => num => state.count + num;}this.$store.addCount(3);mapGetters 辅助函数import { mapsGetters } from 'vuex';export default { computed: { ...mapGetters([ 'doubleCount', 'addCount', ]) }}
如果你想将一个 getter 属性另取一个名字,使用对象形式:
mapGetters({ // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount` storeDoubleCount: 'doubleCount'})以上是"Vuex中的State和Getter有什么用"这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.