vux中关于组件中调用getter如何进行传值

vux中关于组件中调用getter如何进行传值

在使用vux中进行状态管理的时候 ,我们不可避免的要使用到getter,它的功能和vue中computed功能类似

在不给getter传参的时候,他默认会接收state和getter做为参数

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    }
  }
})
//在组件中可以通过辅助函数mapGetters
 computed: {
    ...mapGetters(["doneTodos"]) //因为mapGetter返回来的是一个对象,我们可以用ES6的扩展运算符进行合并
  },
  methods: {
    do() {
      this.doneTodos();
    }
  },
//或者
  methods: {
    do() {
      this.$store.getters.doneTodos(); //注意,getter 在通过方法访问时,每次都会去进行调用,而不会缓存结果。
    }
  },

在组件中调用getter的时候需要向getter中传参

我们可以在getter中返回以一个函数,在返回的函数中接收组件中调用时传递过来的参数

//我的store
const store = new Vuex.Store({
state: {
        num: [1, 2, 3, 4, 5, 6],
    },
   getters: {
        getNum (state, getters) {
            return (condition) => {
                return state.num.filter(item => {
                    return item > condition
                })
            }
        }
    },
})
// 取getter中的getNum
 computed: {
    ...mapGetters(['getNum'])
  },
 // 调用
methods: {
    test() {
      console.log(this.getNum, 9999)
      console.log(this.$store.getters.getNum, 888)
      console.log(this.getNum(2), 777)
      console.log(this.$store.getters.getNum(2), 666)
    }
  }
//  控制台输出
ƒ (condition) {
        return state.num.filter(function (item) {
          return item > condition;
        });
      } 9999
index.vue?6ced:41 ƒ (condition) {
        return state.num.filter(function (item) {
          return item > condition;
        });
      } 888
index.vue?6ced:42 (4) [3, 4, 5, 6] 777
index.vue?6ced:43 (4) [3, 4, 5, 6] 666
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值