少学习多摸鱼

day97 - 求和案例-getters版本

求和案例-getter版本

之前的使用计算属性来写对state中的数据进行加工再使用

但对于共享数据,可以在getter中配置一个函数,由多个组件调用

减少代码量,提高复用率

 computed:{
   //靠程序员自己去写计算属性
   /*sum(){
     return this.$store.state.sum
   },
   subject(){
     return this.$store.state.subject
   },
   school(){
     return this.$store.state.school
   },
    */
   //借助mapState生成计算属性,从state中读取数据,对象写法
   // ...mapState({sum: 'sum', school: 'school', subject: 'subject'}),
//借助mapState生成计算属性,从state中读取数据,数组写法
   ...mapState(['sum','school','subject']),
   /*bigSum(){
     return this.$store.getters.bigSum
   },
    */
   ...mapGetters(['bigSum'])

 

总结

 /*
 getters:
 1.概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
 2.在store.js中追加getters配置
     //准备getters--用于将state中的数据进行加工
     const getters = {
         bigSum(state){
             return state.sum*10
         }
     }
     Vue.use(vuex)
     //创建并导出store
     export default new vuex.Store({
         actions,
         mutations,
         state,
         getters,
     })
 3.组件中读取数据:$store.getters.bigSum
  */

 

 
posted @ 2023-03-16 17:30  北海之上  阅读(38)  评论(0)    收藏  举报
/* 粒子吸附*/