zoukankan      html  css  js  c++  java
  • vuex中getter的用法

    Vuex 允许我们在store中定义“getter”(可以认为是store的计算属性)。就像计算属性一样,getter的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。

    getters的作用

    对于getters的理解主要作用是对state属性进行计算,可以理解类似于Vue中computed。接下来让我通过一个例子如何使用这两个功能的。

    还是以我们上一讲的累加器为例,在getter.js中增加getCount,内容如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    const getters = {
      getNum (state) {
        return state.num
      },
      getCount (state) {
        return state.count
      }
    }
     
    export default getters

    在组件中如何使用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    <template>
      <div class="getter">
        {{ count }}
        <button @click="add">ADD State</button>
      </div>
    </template>
     
    <script>
    export default {
      data () {
        return {}
      },
      computed: {
        count () {
          return this.$store.getters.getCount
        }
      },
      methods: {
        add () {
          this.$store.commit('add')
        }
      }
    }
    </script>

    this.$store调用

    1
    this.$store.getters.getCount

    引用store来调用

    1
    2
    3
    import store from '@/store/store.js'
     
    store.getters.getCount

    mapGetters 辅助函数

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <template>
      <div class="getter">
        {{ getCount }}
        <button @click="add">ADD State</button>
      </div>
    </template>
     
    <script>
    import { mapGetters } from 'vuex'
    export default {
      data () {
        return {}
      },
      computed: {
        ...mapGetters(['getCount'])
      },
      methods: {
        add () {
          this.$store.commit('add')
        }
      }
    }
    </script>
  • 相关阅读:
    js实现中文转拼音
    JS中的call、apply、bind方法
    python 过滤html方法
    css 多出一行或多行后显示...的方法
    js 中文排序
    eclipse小技巧
    npm安装及webpack打包小demo
    zan扩展安装
    vagrant安装centos7
    centos7 nginx访问目录403解决
  • 原文地址:https://www.cnblogs.com/jhflyfish/p/12686877.html
Copyright © 2011-2022 走看看