vuex中的mapState和mapGterrs

<template>
  <div class="count">
    <h2 > 当前求和为 :{{sum}}</h2>
    <h3 > 当前求和放大十倍为为 :{{bigSum}}</h3>
    <h3 > 我在:{{address}} 学习:{{subject}}</h3>
    <select v-model.number="n">
      <option :value="1">1 </option>
      <option :value="2">2 </option>
      <option :value="3">3 </option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前求和为奇数再加</button>
    <button @click="incrementWate">等一等再加</button>
  </div>
</template>

<script>
import {mapState, mapGetters} from 'vuex'

export default {
    name:"Count",
    data() {
      return {
        n:1,//用户选择的数字
        
      }
    },
    computed:{
      /* 自己写的计算属性 */
      /* sum(){
        return this.$store.state.sum
      },     
      address(){
        //  console.log(this.$store)
        return this.$store.state.address
      },
      subject(){
        return this.$store.state.subject
      }, */
      /* **************************** */
      // 借助mapState生成计算属性,从state中读取数据(对象写法)
      /* ...mapState({
        sum:"sum",
        address:"address",
        subject:"subject",
      }), */
      // 借助mapState生成计算属性,从state中读取数据(数组写法)
      ...mapState(["sum","address","subject"]),

      /* ******************************************* */
      // bigSum(){
      //   return this.$store.getters.bigSum
      // },

      /* ...mapGetters({
        bigSum:"bigSum",
      }), */

    ...mapGetters(["bigSum"]),

    },
    methods: {
      increment(){
        // this.$store.dispatch('jia',this.n)
        this.$store.commit('JIA',this.n)
      },
      decrement(){
        this.$store.commit('JIAN',this.n)
      },
      incrementOdd(){
       
        // if (this.Sstore.state.sum%2) {
           this.$store.dispatch('jiaOdd',this.n)
        // }
      },
      incrementWate(){
        // setTimeout(() => {
         this.$store.dispatch('jiaWate',this.n)
        // }, 500);
      },
    },
    mounted() {
      // console.log(this.$store) 
    },
    
}
</script>

<style scoped>
   button{
     margin: 5px;
   }
</style>

 

posted @ 2022-11-16 10:06  小白字太白  阅读(23)  评论(0)    收藏  举报