xinpianchang / fe-weekly

weekly for fe-team
10 stars 2 forks source link

vuex getters #105

Open dailynodejs opened 2 years ago

ddd-000 commented 2 years ago
  1. 作用:把多个组件都使用的需要二次计算的state数据抽提出来共享。
const store = new Vuex.Store({  
    state: {  
    list:[1,3,5,7,9,20,30]  
    }  
})

在index.vue中过滤:

export default {  
    name: "index.vue",
    computed: {
        list() {
            return this.$store.state.list.filter(item => item > 5);
        }
    }
}

如果其他组件也想用过滤后的数据,就得把过滤代码复制出来,如果业务规则发生改变,得一一修改,难以维护,这时就可以用getters属性将数据抽提出来共享。

const store = new Vuex.Store({
    state: {
    list: [1, 3, 5, 7, 9, 20, 30]
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item > 5)
        }
    } 
})

index.vue

export default {
    name: "index.vue",
        computed: {
        list() {
            return this.$store.getters.filteredList;
        }
    }
}

2.内部依赖:getter可以依赖已经定义好的getter

const store = new Vuex.Store({
    state: {
        list: [1, 3, 5, 7, 9, 20, 30]
    },
    getters: {
        filteredList: state => {
            return state.list.filter(item => item > 5)
        },
        listCount: (state, getters) => {
            return getters.filteredList.length;  
        }   
    }
})

index.vue

export default {
    name: "index.vue",
    computed: {
        list() {
            return this.$store.getters.filteredList;
        },
        listCount() {
            return this.$store.getters.listCount;
        } 
     }  
}

3.访问方式

//1. 通过属性访问
store.getters.doneTodos
//2. 通过方法访问
store.getters.getTodoById(2)
//3.辅助函数:mapGetters
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters([
      'doneTodosCount',
    ])
  }
}

4.创建步骤

image

//store/index.js
import getters from './getters'
const store = new Vuex.Store({
  modules,
  getters
})

image