Vue 之 Vuex(4)Getter 的使用

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤、计数等操作。

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

<!DOCTYPE html>
<html lang="en" xmlns="">
<head>
    <meta charset="UTF-8">
    <title>Vuex:getters 的使用</title>
</head>
<body>
<div id="app">
    <button-counter></button-counter>
</div>

<script src="vuex.js"></script>
<script src="vue.js"></script>
<script>
  Vue.component('ButtonCounter', {
    computed: {
      // 直接使用计算属性使用 getter
      sellingBooks () {
        return this.$store.getters.sellingBooks
      },
      // 使用对象展开运算符将 getter 混入 computed 对象中
      ...Vuex.mapGetters([
        'sellingBooksCount',
        'getBookById'
      ])
    },
    template: `
      <div>
      <h3>sellingBooks: </h3><p>{{ sellingBooks }}</p>
      <h3>sellingBooksCount: </h3><p>{{ sellingBooksCount }}</p>
      <h3>getBookById: </h3><p>{{ getBookById(3) }}</p>
      </div>
    `
  })

  // 创建Vuex容器
  const store = new Vuex.Store({
    strict: true,
    state: {
      books: [
        {id: 1, title: 'Vue.js 从入门到秃顶', isSold: false},
        {id: 2, title: 'Spring Boot 从入门到入土', isSold: true},
        {id: 3, title: 'MySQL 从入门到删库跑路', isSold: true},
      ]
    },
    // 有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤、计数等操作:
    // Getter 接受 state 作为其第一个参数
    getters: {
      // 过滤
      // sellingBooks: state => { return state.books.filter(book => book.isSold === true) },
      sellingBooks: state => state.books.filter(book => book.isSold === true),
      // 复用 getters
      // sellingBooksCount: (state, getters) => { return getters.sellingBooks.length },
      sellingBooksCount: (state, getters) => getters.sellingBooks.length,
      // 传值
      // getBookById: (state) => (id) => { return state.books.find(book => book.id === id) }
      getBookById: state => id => state.books.find(todo => todo.id === id)
    },
  })

  new Vue({
    el: '#app',
    store
  });

</script>
</body>
</html>

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值