美文网首页
六、mapState辅助函数的使用 ------ 2020-05

六、mapState辅助函数的使用 ------ 2020-05

作者: 自己写了自己看 | 来源:发表于2020-05-07 21:00 被阅读0次

1、mapState辅助函数的作用:

当一个组件需要获取多个状态的时候,将这些状态都声明为计算属性会有些重复和冗余。
为了解决这个问题,我们可以使用 mapState 辅助函数帮助我们生成计算属性,让你少
按几次键:

2、mapState辅助函数的基础使用:

(1)、在需要使用mapState辅助函数的组件中导入mapState辅助函数
import { mapState } from 'vuex'

(2)、在computed中映射我们state
computed: {
     ...mapState(['count']),
}

<script>
import {mapState} from 'vuex'

console.log(mapState('count'))
// {'count': f}

export default {
    computed: {
        ...mapState(['count']), // 等同于下面的这种方式
        // count: function () {
        //     return this.$store.state.count
        // }
    }
}
</script>

3、使用mapState生成computed时修改state中值的名字

<script>
import { mapState } from "vuex";

console.log(mapState("count"));
// {'count': f}

export default {
  computed: {
    ...mapState({ c: "count" }) // 修改映射出的state中的值
    // ...mapState(['count']),
    // count: function () {
    //     return this.$store.state.count
    // }
  }
};
</script>

4、mapState映射深层state

<script>
import { mapState } from "vuex";

console.log(mapState("count"));
// {'count': f}

export default {
  computed: {
      ...mapState({'c': state => state.a.a}) // 值为一个函数
    // ...mapState({ c: "count" })
    // ...mapState(['count']),
    // count: function () {
    //     return this.$store.state.count
    // }
  }
};
</script>

相关文章

网友评论

      本文标题:六、mapState辅助函数的使用 ------ 2020-05

      本文链接:https://www.haomeiwen.com/subject/fypzghtx.html